【发布时间】:2021-11-29 03:14:22
【问题描述】:
我一定是疯了,或者真的很累。所以我遇到了这种情况,我得到了分配给用户的所有角色的集合。那部分没问题....但是我注意到一些非常奇怪的东西。
我正在使用 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;
});
但这给了我这个奇怪的带有错误 ID 的枢轴合并版本。
$this->roles->each(function($role) {
echo $role;
});
【问题讨论】:
-
您是否在用户或角色模型中反对 $with 属性?
-
@OMR 我没有。不过,我在帖子中添加了额外的内容。我不确定两者之间有什么区别,但这与关系的运作方式有关。
-
可能是我试图使用模型内部的关系吗?
标签: mysql laravel eloquent many-to-many relationship