Laravel多对多合并Pivot?



我一定是疯了或者真的很累了。所以我有这种情况,我得到分配给用户的所有角色的集合。这部分没问题....然而,我注意到一些超级奇怪的事情。

我正在使用Laravel 8和PHP8(不是奇怪的部分)。

出于某种原因,我不只有从其他表结果也主数据合并。我不知道为什么会这样。下面是示例:

用户模型关系:

/**
* Relationship with roles model.
*
* @return BelongsToMany
*/
public function roles(): BelongsToMany
{
return $this->belongsToMany(
Role::class,
'role_user',
'user_id',
'role_id'
)->withTimestamps();
}

角色模范的关系:

/**
* Relationship with users table.
*
* @return BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(
User::class,
'role_user',
'role_id',
'user_id'
)->withTimestamps();
}

在用户模型中,我有这个。

$this->roles->each(function($role) {
dd($role);
});

我期望得到相关模型的转储,然而由于一些奇怪的原因,我得到的是数据透视表与模型合并:

"id" => 7 // this is the relation ID from the pivot table
"display_name" => "Administrator" // this is from Role model
"code" => "admin" // role model
"description" => "Super User - can do everything in the system. This role should only be assigned to IT staff member." // role model
"created_at" => "2021-10-01 11:00:00" // pivot table
"updated_at" => null // pivot table
"deleted_at" => null // pivot table
"role_id" => 1 // pivot table
"user_id" => 2 // pivot table

要么我做错了什么,要么我错过了一些非常明显的东西。谁知道世界上发生了什么?

只是补充一下:数据来自两个地方,但结果只是一个角色模型。

我不应该把主角的角色去掉吗?它覆盖了我的角色模型字段。

编辑:

括号似乎有所不同。数据仍然合并。然而,当我这样做时,看起来来自最终模型的数据被合并(因此它覆盖)到来自枢轴的数据。所以我得到了正确的ID

$this->roles()->each(function($role) {
echo $role;
});

但这给了我一个奇怪的pivot合并版本,ID错误。

$this->roles->each(function($role) {
echo $role;
});

我知道那是什么。我不假思索地将ID列添加到数据透视表中。

这个来自pivot的ID覆盖了我的end model的ID。我把它去掉后,问题就解决了。

我不知道为什么Laravel将默认添加这些字段和与主列合并……我想它就是无缘无故地这么做。虽然我不明白如果有一个单独的机制来访问数据透视表(模型上的数据透视关系)有什么意义。

这让我觉得我做错了什么。但是,是的,希望它能有所帮助。如果有人知道为什么Laravel会自动添加pivot内容,请告诉我。

最新更新