Laravel分离不处理belongsToMany



我有这个模型:Company
它有一个关系:$this->belongsToMany('AppCallList', 'call_list_companies', 'company_id', 'call_list_id')

反之亦然:CallList
关系:$this->belongsToMany('AppCompany', 'call_list_companies', 'call_list_id', 'company_id')

我可以将Company连接到CallList
但我无法从CallList分离Company

为什么?

我用于分离公司的代码:
$company->call_lists()->detach($call_list);

我还尝试了另一种方法:
$call_list->companies()->detach($company);

当我这样做的时候,它只是返回null。我检查了公司和通话列表是否存在,数据库中是否存在这两者之间的关系。

有人知道我做错了什么吗?我也没有任何错误。

如果值得一提的话,我还使用了一个用于关系的透视表。

将关系查询向下筛选到具有匹配ID的调用列表,然后调用detach()

尝试:

$company->call_lists()->where('id', $call_list->id)->detach();

在过去的两年里,我遇到过两次类似或相同的问题。

我发现这个关系使用了软删除,这就造成了这个问题。

我的关系belongsToMany使用了Pivot类。

use IlluminateDatabaseEloquentRelationsPivot;
use IlluminateDatabaseEloquentSoftDeletes;
class EntityUser extends Pivot
{
use SoftDeletes; // it makes the problem
// some code
}

该表的列为deleted_at。但问题被定为SoftDeletes类。

当我运行$user->entities()->detach($entity)时,它返回1,这意味着一条记录被触摸或删除,但表和实际结果没有变化。

我去掉了SoftDeletes,它起了作用。我还从表中删除了该列。

解决方案

  • 从数据透视类中删除SoftDeletes。拉拉威尔没有得到官方的支持。https://github.com/laravel/nova-issues/issues/2750
  • 从数据透视表中删除deleted_at。https://laravel.com/docs/9.x/migrations#available-命令别名

最新更新