使用Laravel Eloquent,可以通过对象集合上的pivot列来筛选Pivot表。
使用Laravel Eloquent,可以通过对象集合上的pivot列来筛选Pivot表。
我有一个问题,正在寻找一个好的解决方案。
我有以下数据库表:
- game_objects
- game_object_attributes
- game_object_game_object_attribute (pivot)
GameObject.php:
public function gameObjectAttributes() { return $this->belongsToMany('App\Models\GameObjectAttribute')->withPivot('value')->withTimestamps(); }
GameObjectAttribute.php:
public function gameObjects() { return $this->belongsToMany('App\Models\GameObject'); }
现在,我正在尝试获取所有GameObjectType的GameObject,并使用枢轴列\"value\"过滤结果。
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->join('game_object_game_object_attribute', 'game_objects.id', '=', 'game_object_game_object_attribute.game_object_id')->where('value', '=', '4')->get());
我在这里使用了一个连接操作,但是否有一种使用Eloquent关系来使用的方法?
这将返回给我所有类型为\'troops\'的GameObject:
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->get();
\'gameObjects()\'会给我返回一个集合,但我不能调用像这样的东西
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->withPivot('value', 3)->get();
或
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->gameObjectAttributes->wherePivot('value', 3)->get();
这里我可以通过迭代集合\'gameObjects()\'并通过foreach检查枢轴是否有value = 3,但必须有比这更好的解决方案。我是laravel的新手..
此外
我尝试获取
- 通过GameObjectType获取所有GameObject=>返回一个集合**
GameObjectType::where(\'name\', $gameObjectTypesEnum)->first()->gameObjects()
- 然后我尝试通过枢轴进行过滤,以仅获取具有给定GameObjectType和枢轴值(例如3)的GameObject。
->join(\'game_object_game_object_attribute\', \'game_objects.id\', \'=\', \'game_object_game_object_attribute.game_object_id\')->where(\'value\', \'=\', \'4\')->get());
我做错了什么,或者这不可能通过Eloquent完成 🙁
提前感谢大家。
最好的问候。
admin 更改状态以发布 2023年5月22日