Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple conditions on Laravel elequent relationship

I am new to Laravel and working on 5.4 version. I have a model "A" and model "B". Model A has hasMany relationship with B. Upto here things are ok. But now, I want to add more conditions on this relationship.

By default, Laravel works only foreign key relation. I mean it matches data on the basis of only 1 condition. Here, I want more condition.

Below are the tables of both Model:

table: A

id      name      Year  
 1      ABC       2016  
 2      DEF       2017  

table: B

 id     A_id     name   Year  
  1       1      tst    2016  
  2       2      fdf    2017  
  3       1      kjg    2017  

By default, If I want to see records of A_id 1 from table B, then Laravel will fetch all records for A_id 1. But now, suppose, if I want to get records for 2016 then How I can I do this using Laravel relationship method?

Below are the Elequent Model for both tables:

class A extends Model{  

    public function b(){  
       return this->hasMany('B');  
    }  
}  


class B extends Model{  
     public function a(){  
       return $this->belongsTo('A');  
     }
}  

Code to fetch records of id 1:  

$data = A::with('b')->find(1)->toArray();  

The above request is giving me all data from table B for id 1 but I also want to put corresponding year condition also.

Is anyone know, Ho can I do this? Please share your solutions.

Thanks

like image 315
Dhirender Avatar asked Oct 29 '25 15:10

Dhirender


1 Answers

You have to constrain your eager loads, using an array as the parameter for with(), using the relationship name as the key, and a closure as the value:

$data = A::with([
    'b' => function ($query) {
        $query->where('year', '=', '2016');
    },
])->find(1)->toArray();

The closure automatically gets injected an instance of the Query Builder, which allows you to filter your eager loaded model.

The corresponding section in the official documentation: https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads

like image 177
Tibor B. Avatar answered Oct 31 '25 07:10

Tibor B.