L5.6 - Relation on pivot table

前端 未结 1 1915
死守一世寂寞
死守一世寂寞 2020-12-20 03:58

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

For example:

shops:

  • id
  • name

<

1条回答
  •  一整个雨季
    2020-12-20 04:30

    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.

    0 讨论(0)
提交回复
热议问题