0

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

Farzin Bidokhti
  • 71
  • 1
  • 10

2 Answers2

1

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

OMR
  • 11,736
  • 5
  • 20
  • 35
0

Model

public function all() { 
     return $this->hasManyThrough('ShopType', 'User', 'Files');
} 

and then

$shop = Shop::with('all')->where('id',$id)->get();
Harut
  • 43
  • 6
  • How can i add it in this code: ```$shop = Shop::where('id', $id)->with('ShopType', 'User', 'Files')->get();``` – Farzin Bidokhti May 04 '20 at 14:12
  • You can use this syntax in Model `public function all() { return $this->hasManyThrough('ShopType', 'User', 'Files'); }` and then `$shop = shop::with('all')->where('id',$id)->get();` – Harut May 04 '20 at 14:17