[英]How to let laravel know that 2 (or many) many-to-many relationships are different when foreign keys are same
首先,我英語不好,很抱歉。
在我的情況下,我通過a_b
表從a
表到b
表有很多關系。 a 上的一行可以belongToMany
b
上a
belongToMany
行,並用a_b
列type
區分它們。
class A extends Model
{
public function bs
{
return $this->belongToMany(B::class)
->withPivot(['type']);
}
}
class B extends Model
{
public function as
{
return $this->belongToMany(A::class)
->withPivot(['type']);
}
}
當我在該關系上運行sync
方法時會出現問題,laravel 無法區分我關聯的 2 個關系是否具有相同的外鍵但 diff type
。
A::find(1)->bs()->sync([
B::find(1)->id => ['type'=>1],
B::find(1)->id => ['type'=>2],
])
A::find(1)->bs()->where('id', 1)->count() // is 1 but I want it is 2
嘗試使用bs
而不是bs()
,否則,您將使用方法鏈接,並且where()
條件將作為查詢構建器應用於相關模型而不是關系集合。
A::find(1)->bs->where('id', 1)->count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.