Laravel 如何实现 relationship 多字段关联?
通常两个model关联 我们用 hasOne 或者hasMany即可
但是 如果Model关联约束超出一个字段该如何解决?
Stack Overflow的帖子有相关解决方案: https://stackoverflow.com/questions/297518...
但是我试过会报错。
举例说明:
存在两个Model: Product和ProductStats,二者通过sku字段一对一关联;但实际上二者还有一个字段shop_id,用以表示所在的销售平台,必须俩字段同时约束,获取到的才是正确的数据。
class ProductStats {
public function product ()
{
return $this->hasOne('\App\Model\Product', 'sku', 'sku')->where('shop_id', $this->shop_id);
}
}
按照上述声明,会出现下列情况:
// 得到的product是null
ProductStats::with('product')->get();
// product可以获取到正确的数据
$res = ProductStats::query()->get();
foreach ($res as &$unit) {
$unit->product;
}
// product 可以获取到正确的数据
ProductStats::with([
'product' => function ($query)use (&$shopId) {
$query->where('shop_id', $shopId);
}
])->get();
显然,第一种方式最为便捷,但需要在Model中对product做正确的封装。
诸位有解决方法不?
github.com/topclaudy/compoships 试试这个