【发布时间】:2017-09-21 04:52:58
【问题描述】:
我有 products 表和 countries 表,它们假设彼此之间存在多对多关系,但包含关系的附加参数。
所以在产品中有产品ID,名称
在国家/地区有国家/地区ID,名称
product_country中有country_id、product_id、price
产品型号:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* Get the countries for the product.
*/
public function countries()
{
return $this->belongsToMany('Country');
}
}
国家模式:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
/**
* Get the countries for the product.
*/
public function products()
{
return $this->belongsToMany('Product');
}
}
所以我知道我可以使用 ->withPivot('价格') 将其添加到枢轴关系中,但我无法弄清楚 - 例如按国家/地区查询产品列表的最佳方法是什么,也许我的结构是错误的,但我希望最终能够获得所有产品当然是针对特定国家/地区的价格。
感觉我需要做很多工作才能按国家/地区为产品定价。
Country::find(1)->products->first()->pivot->price
【问题讨论】:
标签: php laravel eloquent many-to-many