Laravel - 如何分离条件?
Laravel - How to detach with condition?
我想根据条件从模型中分离值。我想从类型为 3 的组织中分离所有人员,即工人。但是当我尝试这样做时,它分离了所有人,没有考虑 where 条件。
这是我的关系:
Class:组织
public function people()
{
return $this->belongsToMany(People::class, 'organization_people')
}
public function workers()
{
return $this->people()->where('type', 3); //returns all workers
}
public function detachWorkers()
{
$this->workers()->detach(); // this detaches all people, I want it to detach only workers
}
您需要这样做:
public function people()
{
return $this->belongsToMany(People::class, 'organization_people')
}
public function workers()
{
return $this->people()->where('type', 3);
}
public function detachWorkers()
{
$this->people()->detach($this->workers);
}
IIUC Laravel 不会将 where
约束附加到 detach
上。但是,它将直接附加您放置在枢轴 table 上的任何约束,例如 $this->people()->wherePivot('type', 3);
假设您在枢轴 table.[=15 上有一个 type
列=]
我想根据条件从模型中分离值。我想从类型为 3 的组织中分离所有人员,即工人。但是当我尝试这样做时,它分离了所有人,没有考虑 where 条件。
这是我的关系:
Class:组织
public function people()
{
return $this->belongsToMany(People::class, 'organization_people')
}
public function workers()
{
return $this->people()->where('type', 3); //returns all workers
}
public function detachWorkers()
{
$this->workers()->detach(); // this detaches all people, I want it to detach only workers
}
您需要这样做:
public function people()
{
return $this->belongsToMany(People::class, 'organization_people')
}
public function workers()
{
return $this->people()->where('type', 3);
}
public function detachWorkers()
{
$this->people()->detach($this->workers);
}
IIUC Laravel 不会将 where
约束附加到 detach
上。但是,它将直接附加您放置在枢轴 table 上的任何约束,例如 $this->people()->wherePivot('type', 3);
假设您在枢轴 table.[=15 上有一个 type
列=]