Laravel雄辩的数据透视表由对象集合上的数据透视列过滤

viko91

我有一个问题,正在寻找一个不错的解决方案。

我有这些数据库表:

  • game_objects
  • 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());

我在这里使用了join,但是有没有一种方法可以实现雄辩的关系呢?

这将返回所有类型为“部队”的GameObjects:

$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的新手。

另外

我试图得到

  1. 通过GameObjectType =>返回集合来获取所有GameObjects **

    GameObjectType :: where('name',$ gameObjectTypesEnum)-> first()-> gameObjects()

  2. 然后,我尝试过滤低谷枢轴,以仅获得具有给定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不可能做到这一点:-(

谢谢大家。

最好的祝福

j

你可以这样

 $gameObjects = GameObject::where('name', $gameObjectTypesEnum)->whereHas('gameObjectAttributes', function($query)
    {
        $query->where('value', 3); 
    })->get();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章