Home > Software engineering >  Laravel how to merge belongs to many relationship with has many relation
Laravel how to merge belongs to many relationship with has many relation

Time:10-23

I'm using Laravel with Eloquent. In my example, I have 4 tables: (report, report_image, shop, report_shop).

Relationship between the four tables listed above:

A report can have multiple images - 1 to many A report can can many shops also A shop can have multiple report - M to My

Table structure down below,

report
------------
id
name
email
description


report_images
------------
id
report_id [FK report ID]
image


shops
------------
id
name
email


report_shop
------------
report_id [FK report ID]
shop_id [FK shop ID]

Now I want to retrieve a shop with report table data and report_image table data. So I used "belongsToMany", Using belongsToMany I can get shop with report data but it dosen't include report_image table. Used code below,

// shops model

    public function reports()
        {
            return $this->belongsToMany(Report::class, 'report_shops');
    
        }

Output:

enter image description here

I want to get report images under the reports.

How can I integrate it? Which relationships should I employ?

CodePudding user response:

assuming you have defined all the relationships methods, you can do this:

$shop = Shop::find($id)->with('reports.images');

this will eager load the relationships.

  • Related