【问题标题】:Laravel Many To Many Merges Pivot?Laravel 多对多合并 Pivot?
【发布时间】: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


【解决方案1】:

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

pivot 中的这个 ID 覆盖了我的最终模型中的 ID。删除后问题就消失了。

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

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

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 2021-01-13
    • 2021-10-02
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多