Reputation: 1100
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
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