【问题标题】:Laravel Eloquent belongsToMany only fetches one resultLaravel Eloquent belongsToMany 只获取一个结果
【发布时间】:2021-08-30 05:56:58
【问题描述】:

我的 belongsToMany 函数在应该返回所有元素时只返回单个元素。

这是我的表结构(简化):

users

  • 身份证
  • ...

groups

  • 身份证
  • ...

users_in_groups

  • 身份证
  • user_id
  • group_id

这是我的功能:


    public function getUsers(): BelongsToMany
    {
        return $this->belongsToMany(
            UserDao::class,
            'users_in_groups',  //table
            'id',               //foreignPivotKey
            "user_id"           //relatedPivotKey
        );
    }

我在结果上调用getResults() 方法,即使这样它在items 数组中也只有一个对象。

当我手动查找时,表格已填满。我错过了什么?

【问题讨论】:

  • return $this->belongsToMany( UserDao::class, 'users_in_groups', //table 'user_id', //foreignPivotKey "group_id" //relatedPivotKey );
  • 我认为即使你可以删除两个 id,因为它的命名约定是匹配的
  • @JohnLobo 这几乎奏效了,我只需要更改“user_id”和“group_id”的顺序。非常感谢!将其发布为答案,我会将其标记为解决方案。
  • @JohnLobo 不,我不能,因为它不是真正的“用户”和“组”,而是特定领域的术语,我不想让你混淆;)
  • oaky.np :)祝你有美好的一天

标签: laravel eloquent eloquent-relationship


【解决方案1】:

看起来问题出在$foreignPivotKey 和$relatedPivotKey

public function belongsToMany($related, $table = null, $foreignPivotKey = null, $relatedPivotKey = null,
                              $parentKey = null, $relatedKey = null, $relation = null)

所以你们的关系应该是

 public function getUsers(): BelongsToMany
    {
        return $this->belongsToMany(
            UserDao::class,
            'users_in_groups',
            "group_id" ,    
            'user_id',               
                   
        );
    }

两者都有

【讨论】:

  • 几乎!但是“group_id”必须在“user_id”之前
  • 更新了我的答案。我想如果你在小组模式中,那么我猜应该是相似的。因为我总是遵循表命名约定。所以很少使用额外的参数
猜你喜欢
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 2017-01-28
  • 2014-01-03
相关资源
最近更新 更多