Reputation: 12403
How am using laravel 5.4,
to write sql query to get data from multiple tables for below query
select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5
Now am using this
Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();
but it is getting too confuse to use
is there any better alternative to use this query by using model..
Upvotes: 2
Views: 682
Reputation: 154
It would be better, since you're in laravel after all, to make use of laravel relationships.
Make sure you have a party model:
php artisan make:model Party
Assuming one lease has one party, In your container lease model add:
public function party(){
return $this->hasOne('App\Party', 'id', 'party_id');
}
Then access your model
ContainerLease::with('party')->where('user_id', '=', 5)->get();
Upvotes: 0
Reputation: 33186
You would have to join the tables to do this.
Containerlease::join('tbl_partys', 'tbl_partys.id', '=', 'tbl_container_lease.party_id')
->where('tbl_container_lease.user_id', 5)
->select('tbl_partys.*', 'tbl_container_lease.*');
->get();
However, an even better way would be to create relations if you are using Eloquent. The documentation for this can be found here: https://laravel.com/docs/5.4/eloquent-relationships
Upvotes: 3