I've a problem and searching for a nice solution for it.
I've these db tables:
- 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');
}
Now I'm trying to get all GameObject of an GameObjectType and filtering the result with pivot column '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());
I've used here an join but is there a way to do it with eloquent's relation?
This is returning me all GameObjects of type 'troops':
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->get();
the 'gameObjects()' returning me a collection and here I can't call something like
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->withPivot('value', 3)->get();
OR
$this->model->where('name', $gameObjectTypesEnum)->first()->gameObjects()->gameObjectAttributes->wherePivot('value', 3)->get();
Here I can iterate through collection 'gameObjects()' and checking with foreach if the pivot has value = 3 but there must be a better solution than this. I'm new to laravel..
Additionally
I try to get
Get all GameObjects by an GameObjectType => returning a collection**
GameObjectType::where('name', $gameObjectTypesEnum)->first()->gameObjects()
Then I try to filtering trough pivot to get only GameObjects with given GameObjectType and with pivot value e.g. 3.
->join('game_object_game_object_attribute', 'game_objects.id', '=', 'game_object_game_object_attribute.game_object_id')->where('value', '=', '4')->get());
I'm doing something wrong or this is not possible to do it with Eloquent :-(
Thank you all in advance.
Best regards