php - 通过数据透视表使用关系
问题描述
真实使用数据透视表模型中的关系?有表:
产品
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;
解决方案
product_store
表和表之间存在一对多关系product_store_price
。而表是和product_store
表之间的中间表。products
stores
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
行,您将需要一对多的关系。product
store
// 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;
}
推荐阅读
- google-apps-script - 添加多个联系人超出时间
- python - 如何以编程方式在 Python 中调用类成员函数?
- android - 如何在 Android Studio 中运行我的 Lint 自定义规则?
- java - 使用 Java 8 模式匹配将 Map 转换为 List
- reactjs - 在链接组件中反应提交表单按钮
- java - 如何使用 map 和 match 执行我的部分代码?
- javascript - 计算历史
- github - 通过获取特定提交从 Jira(集成 Jira、Github、Jenkins)构建和发布
- java - 逆时针方向旋转矩阵的元素
- javascript - 我无法使用 ajax 访问控制器功能