Search code examples
laravelmodelrelationdata-retrievalwherehas

How can i put condition in relation in laravel?


I have File model that it store my images, and i have shop model, the shop can have many images and in shop model i wrote this code:

public function Files()
    {
        return $this->hasMany('system\models\file', 'attachment_id');
    }

and i want retrieve shop model with it's images, now my question is how can i put where condition in relation. my code for retrieve shop model is:

$shop = Shop::where('id', $id)->with('ShopType', 'User', 'Files')->get();


note: i need to put 2 condition for relation that one of theme set in Files method that call attachment_id and my second condition is attachment_type please help me. thanks


Solution

  • you could use constraining-eager-loads:

    $shop = Shop::with(['ShopType','User', 'Files'=>function ($query)use($id)
    {
    query->where('id', $id);
    }
    ])->get();
    

    more details in:

    https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads