vlauciani
vlauciani

Reputation: 1100

L5.6 - Relation on pivot table

I've a relation on a pivot table; how I can expand It?

For example:

shops:

products:

product_shop:

table_A:

The relation Many-to-Many in the Shops Model is:

class Shops extends Model {
    public function products()
    {
        return $this->belongsToMany('Products', 'product_shop', 'product_id', 'shop_id')->withPivot(
            'field_1',
            'field_3',
            'field_3',
            'table_A_id'
            )
            ->as('product_shop')
            ->withTimestamps();
    }

}

and the query to retrieve all data is:

class GetData extends Model {
     public static function getAll() {
         $query = Shops::with(
            'products'
            )->get();
     }
}

This return the product_shop.table_A_id but I'd like to expand the foreign key and retrieve table_A.name; is there a way?

Thank you.

Upvotes: 2

Views: 488

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

You can use a pivot model:

class ProductShopPivot extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    public function tableA()
    {
        return $this->belongsTo(TableA::class);
    }
}

class Shops extends Model
{
    public function products()
    {
        return $this->belongsToMany('Products', 'product_shop', 'product_id', 'shop_id')
            ->withPivot(
                'field_1',
                'field_3',
                'field_3',
                'table_A_id'
            )
            ->as('product_shop')
            ->withTimestamps()
            ->using(ProductShopPivot::class);
    }
}

Then access it like this:

$shop->product_shop->tableA->name

Unfortunately, there is no way to eager load the tableA relation.

Upvotes: 2

Related Questions