1

I have 3 collections:

+----------------+  +----------------+  +----------------+ 
|     Posts      |  |   PostImages   |  |   PostFiles    |
+----------------+  +----------------+  +----------------+
|   id           |  |   id           |  |   id           |
|   title        |  |   post_id      |  |   post_id      |
|   description  |  |   patch        |  |   patch        |
|   user_id      |  +----------------+  |   description  |
+----------------+                      +----------------+

Controllers:

$posts = User::find($userdata->id)->posts;

$postids = Post::where('user_id', $userdata->id)->pluck('id')->toArray();

$images = PostImage::wherein('post_id ', $postids )->get()->All();

$files = Docs::wherein('post_id', $postids )->get()->All();

Is it possible to combine these three collections without using the loop, to get this structure:

[post1] => [
    title => title,
    content => content,
    images => collection [
                        image1 => patch,
                        image2 => patch,
                        image3 => patch,
                        ],
    Files => [
        [0] => [
            file1 => patch,
            description1 => description
        ],
        [1] => [
            file2 => patch,
            description2 => description
        ]
    ]
],
[post2] => [
    title => title,
    content => content,
    images => collection [
                        image1 => patch,
                        image2 => patch,
                        image3 => patch,
                        ],
    Files => [
        [0] => [
            file1 => patch,
            description1 => description
        ],
        [1] => [
            file2 => patch,
            description2 => description
        ]
    ]
],

Any ideas?

1
  • 1
    I believe all of these are related. Possible to fetch everything in one query using joins ? That way you will avoid loops and also save no. of queries. Refer: Eloquent Relationships or Query Builder Joins Commented Aug 19, 2018 at 5:51

1 Answer 1

3

Yes, Laravel's 'WITH' is just what you need.

Example:

In you post model add these functions.

public function images()
{
  return $this->hasMany(YouImageModel::class, 'post_id');
}

public function files()
{
 return $this->hasMany(YourFileModel::class, 'post_id');
}

So when getting post you can eager load the images.

$posts = Post::where('user_id', $userdata->id)->with(['images', 'files])->posts;

Here is the doc link

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

Comments

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.