Laravel轻松分离HasManyThrough关系

时间:2019-03-16 15:00:03

标签: laravel eloquent laravel-5.7

场景 假设有一个系统,公司可以将其他公司添加到他们的收藏夹列表中。要获取此记录,我将执行以下操作:

// Returns a list of favorite companies for the current user's company 
$user->company()->favorites;

请注意,favorites代表hasManyThrough关系。

public function favorites()
{
  return $this->hasManyThrough(Company::class, CompanyFavorite::class, 'company_id_owner', 'id', 'id', 'company_id_selected');
}

理想解决方案,我正在寻找一种解决方案,其中可以使用hasManyThrough对象从中介关系表中删除记录。示例:

$user->company()->favorites()->detach([...companies_ids]);

1 个答案:

答案 0 :(得分:0)

HasManyThrough在这里不是正确的关系,请改用BelongsToMany

public function favorites()
{
    return $this->belongsToMany(
        Company::class, 'company_favorites', 'company_id_owner', 'company_id_selected'
    );
}

这种关系provides是所有必需的方法,例如attach()detach()

$user->company()->favorites()->detach([...companies_ids]);