【发布时间】:2018-11-24 04:21:27
【问题描述】:
我有一个问题,正在寻找一个好的解决方案。
我有这些数据库表:
- 游戏对象
- game_object_attributes
- game_object_game_object_attribute(枢轴)
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 的关系来做呢?
这将返回所有类型为“部队”的游戏对象:
$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 检查枢轴的值 = 3,但必须有比这更好的解决方案。我是 laravel 的新手..
另外
我试着得到
-
通过一个 GameObjectType 获取所有 GameObjects => 返回一个集合**
GameObjectType::where('name', $gameObjectTypesEnum)->first()->gameObjects()
-
然后我尝试通过枢轴过滤以仅获取具有给定 GameObjectType 和枢轴值的游戏对象,例如3.
->join('game_object_game_object_attribute', 'game_objects.id', '=', 'game_object_game_object_attribute.game_object_id')->where('value', '=', '4')->get( ));
我做错了,或者这不可能用 Eloquent 来做 :-(
提前谢谢大家。
最好的问候
【问题讨论】: