kunal kunal - 1 month ago 6
PHP Question

how to fetch data from multiple tables in laravel

I have three tables
1. users
id
name
email
2. Listings
id
user_id
name
3 ListingImage
id
list_id
image


Here i want a data in one query. where all data fetched based on users table (id) .
i want data something like that

enter code here
Array
(
[user] => Array
(
[id] => 1
[name] =>abc
[email] => abc@gmail.com
[listing]=>
Array
(
[id] => 1
[user_id] => 1
[name] => abc list
[listingimage] =>

[0] => Array
(
[id] => 1
[list_id] => 1
[image] => abc.jpg
)
[1] => Array
(
[id] => 2
[list_id] => 1
[image] => abc.jpg

)

)
)
)


i have used hasMany but it will not give me accurate result can anyone help me

Answer

Considering relations are one to many and you've Listing model class and ListingImage model class for Listings table ListingImage table respectively.

In your User model

public function listings()
{
    return $this->hasMany(Listing::class);
}

In your Listing Model

public function images()
{
    return $this->hasMany(ListingImage::class, 'list_id', 'id')
}

And now

$user = User::with('listings.images')->findOrFail($id);

will give you your desired results.

You can find more details here: https://laravel.com/docs/5.3/eloquent-relationships#one-to-many