L5.6 - 数据透视表的关系

时间:2018-05-22 05:07:15

标签: php laravel eloquent relation laravel-5.6

我在 pivot 表上有关系;我怎么能扩展呢?

例如:

商店

  • ID
  • 名称

产品

  • ID
  • 名称

product_shop

  • PRODUCT_ID
  • shop_id
  • field_1
  • field_2
  • field_3
  • table_A_id

TABLE_A

  • ID
  • 名称

Shops模型中的多对多关系是:

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();
    }

}

以及检索所有数据的查询是:

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

这会返回product_shop.table_A_id,但我想展开外键并检索table_A.name;有办法吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用数据透视模型:

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);
    }
}

然后像这样访问:

$shop->product_shop->tableA->name

不幸的是,没有办法急于加载tableA关系。