【问题标题】:Laravel Relations has problem with retrieve dataLaravel Relations 检索数据有问题
【发布时间】:2021-07-04 00:05:20
【问题描述】:

我的模型中有 BelnogstoMany 关系,我是这样定义的

class MailUsers extends Model
{
      public function group ()
        {
            return $this->belongsToMany('App\Models\Group', 'user_groups','user_id','group_id');
        }

}

在另一个模型中,我定义了这样的关系

class Group extends Model
{  
 public function customer ()
    {
        return $this->belongsToMany('App\Models\MailUsers', 'user_groups','group_id','user_id');
    }

}

当我保存数据时,它会毫无问题地将关系保存在 user_groups 表中,并且我有这些数据

从用户组中选择 *;

+----+---------+----------+
| id | user_id | group_id |
+----+---------+----------+
|  1 |       5 |        1 |
|  2 |      16 |        1 |
+----+---------+----------+

我的问题是当我尝试检索具有关系的数据时,即使它在表中有关系,它也会返回 null

 $data=MailUsers::with(['group'])->get();

即使记录有我上面显示的关系,它也会在组中继续返回 null

如果我尝试使用 toSql 函数打印 SQL 语句,它会在没有任何连接的情况下返回它

select * from mail_users; 

我不知道为什么会这样,我在 laravel 中处理关系,这是我第一次遇到这个问题

【问题讨论】:

    标签: mysql laravel laravel-query-builder


    【解决方案1】:

    尝试建立关系而不将它们放入[]

    $data = MailUsers::with('group')->get();
    

    然后,你可以得到如下组

    $data->pluck('group');
    

    【讨论】:

    • 同理,组内查询返回null
    猜你喜欢
    • 2021-01-04
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2015-11-27
    • 2021-10-17
    • 2011-07-25
    相关资源
    最近更新 更多