13

I have Banks table and separate table with services

$bank = Banks::find(1);
echo $bank->service(1); // print bank with that service (serviceId 1)

It is posible to eager load all banks with service_id =1 ..somewhat like

Bank::with('service(1)')->get();

Thank you in advance

sumit
  • 15,003
  • 12
  • 69
  • 110

3 Answers3

18

Sure! The with method accepts a closure to filter eager loading.

Bank::with(array('service' => function($query){
    $query->where('id', 1);
}))->get();
lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • 6
    You can add/pass your own parameter using "use" ` Bank::with(array('service' => function($query) use ($param){ $query->where('id', $param); }))->get(); ` – Tom Nov 29 '16 at 15:57
  • 1
    @Tom, you saved my day! I have been looking for this for one hour and until now I haven't found anyone who specifies how to pass a parameter here. Thanks!!! – Janbalik Jan 26 '21 at 12:28
0

Use WhereIn to your Model and you shall pass any number inside the Array.

$Data = Banks::whereIn('service_id ', array(1, 2, 3))->get();
var_dump($Data);

I am using var_dump and you shall choose your own coloumn to get your need.

Docs : Eloquent, Advance Where

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
0

You can use this

return User::with(['posts' => function($query){
              $query->whereNotIn('id',[1]);
            }])
           ->get();
Mahedi Hasan Durjoy
  • 1,031
  • 13
  • 17