简体   繁体   中英

How to let laravel know that 2 (or many) many-to-many relationships are different when foreign keys are same

Firstly I'm not well English, sorry about that.

In my case I have relationships many-many from a table to b table through a_b table. A row on a can belongToMany a row on b and differentiate them with type column on a_b .

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']);
   }
}

The issue occur when i run sync method on that relationship, laravel can not differentiate if I relate 2 relationships has the same foreign keys but 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM