0
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] => [email protected]
            [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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

work fine Mahfuzul Alam. Now i am facing one problem i want only one listing with multiple images. it returns me listing index start with 0
if you want only one listing then change hasMany to hasOne in listings() relation. Simple!
Thank you so much :) it means a lot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.