首页 > 解决方案 > 通过数据透视表使用关系

问题描述

真实使用数据透视表模型中的关系?有表:

产品

ID 蛞蝓
1 1-产品

店铺

ID 姓名
1 产品

产品商店

ID product_id store_id 代码
1 1-产品 1 123456
2 1-产品 2 123456

product_store_price

ID product_store_id 价格
1 1 100

型号产品有

public  function stores()
    {
    return $this->
belongsToMany(
'App\Models\Store',
'product_store_links',
'product_id',
'store_id'
)->withPivot('code','id');
    }

模型产品商店

    public function prices()
    {
        return $this->
        hasMany('App\Models\ProductStorePrice','product_store_link_id','id');
    }

我可以使用这样的东西吗?

$product= Product::find(1)->stores[0]->pivot->prices;

标签: phplaraveleloquent

解决方案


product_store表和表之间存在一对多关系product_store_price。而表是和product_store表之间的中间表。productsstores

products在和表之间的多对多关系stores中,product_store表只是一个中间表,有时会被省略并通过数据透视表访问它们的附加字段。但在这种情况下,您将需要一个模型,因为它也将与表product_store有关系。product_store_price

要在 Laravel 中为数据透视表创建模型,您必须使用Pivot. ProductStorePrice然后你可以与模型建立一对多的关系。

use Illuminate\Database\Eloquent\Relations\Pivot;

class ProductStore extends Pivot
{
    public function prices()
    {
        return $this->hasMany(ProductStorePrice::class);
    }
}

要从或访问product_store行,您将需要一对多的关系。productstore

// Product model, Store model

public function productStores()
{
    return $this->hasMany(ProductStore::class);
}

然后你可以通过

$productStores = $product->productStores; // from product
$productStores = $store->productStores; // from store

foreach($productStores as $productStore) {
    $productStore->prices;
}

推荐阅读