对象集合上按透视列筛选的Laravel Eloquent透视表
我有一个问题,正在寻找一个很好的解决方案 我有这些数据库表:对象集合上按透视列筛选的Laravel Eloquent透视表,laravel,eloquent,Laravel,Eloquent,我有一个问题,正在寻找一个很好的解决方案 我有这些数据库表: public function gameObjects() { return $this->belongsToMany('App\Models\GameObject'); } 游戏对象 游戏\对象\属性 游戏\对象\游戏\对象\属性(轴) GameObject.php: public function gameObjectAttributes() { return $
public function gameObjects()
{
return $this->belongsToMany('App\Models\GameObject');
}
- 游戏对象
- 游戏\对象\属性
- 游戏\对象\游戏\对象\属性(轴)
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,并使用pivot列“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();
或
在这里,我可以遍历集合“gameObjects()”并使用foreach检查pivot的值是否为3,但肯定有比这更好的解决方案。我是拉威尔的新手
另外
public function gameObjectAttributes()
{
return $this->belongsToMany('App\Models\GameObjectAttribute')->withPivot('value')->withTimestamps();
}
我试着去
如果我没有误解的话,向你致以最诚挚的问候
->wherePivot('value',4)
除了您的查询之外,还有一种雄辩的加入方式。您可以这样做
$gameObjects = GameObject::where('name', $gameObjectTypesEnum)->whereHas('gameObjectAttributes', function($query)
{
$query->where('value', 3);
})->get();
我也这么认为。生成的Sql是这样的:“从“游戏对象”中选择*,其中“游戏对象”。“游戏对象类型”id“=”和“游戏对象”。“游戏对象类型”id“不为空且“轴”=?”没有连接到pivot表..而且我不知道为什么..eloquent可能会也可能不会使用直接匹配的sql查询来获取所需的信息。在使用信息时,它可以使用其他小查询。(即时加载,延迟加载主题)。但我假设您已使用wherePivot方法对样本数据进行了测试,但无法获得所需的结果。如果是这种情况,我现在没有其他解决方案。是的,我已使用wherePivot和withPivot对其进行了测试…:-(我已使用您的解决方案:GameObjectType::where('name',$gameObjectTypesEnum)->first()->gameObjects()->with(数组('gameObjectAttributes'=>function($query){$query->where('value',3);})->get());返回所有游戏对象,不考虑where value=3。SQL:“从“游戏对象”中选择*,其中“游戏对象”;“游戏对象类型”=?和“游戏对象”。“游戏对象类型”\u id”不为空这就是诀窍!非常感谢!但我不明白为什么whereHas起作用?要补充说明: