【问题标题】:Laravel get all data through pivot TableLaravel 通过数据透视表获取所有数据
【发布时间】:2021-09-10 15:46:32
【问题描述】:

您好,我在获取Recipent 所属组的名称时遇到问题。

我为该主题使用了 3 个表格:recipent、group 和 group_recipent。

在 group_recipent 表中,我只有 recipent_id 和 group_id 之类的列。一切都符合 Laravel 命名约定。

这是我的食谱模型:

 public function groups()
{
    return $this->belongsToMany(Group::class)->withPivot('group_recipent', 'recipent_id', 'group_id');
}

还有我的 Group 模型:

public function recipents()
{
    return $this->belongsToMany(Recipent::class)->withPivot('group_recipent', 'recipent_id', 'group_id');
}

访问数据:

$user = Recipent::find(4);
    
    $data="";

    foreach ($user->groups as $group)
    {
        $data .= $group->name ." ";
    }
    dd($data);

尝试通过数据透视表访问组的名称后出现错误:

照亮\数据库\查询异常 SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列'group_recipent.group_recipent'(SQL:选择groups.*,group_recipent.recipent_id为pivot_recipent_id,group_recipent.@987654329 @ as pivot_group_id, group_recipent.group_recipent as pivot_group_recipent from groups inner join group_recipent on groups.id = group_recipent.@98765430@group_idgroup_id哪里= 4)

我想获取recipent所属组的所有名称,但我得到了类似上面的错误。你知道如何解决这个问题吗? :/

【问题讨论】:

  • 你能在 foreach 中添加组吗?
  • 不,我不知道为什么
  • 好的,您在数据透视表中是否有任何与recipent_id 4 关联的记录?如果没有添加它。之后: $user = Recipent::find(4); $data=""; foreach ($user->groups as $group) { dd($group); }

标签: php laravel eloquent pivot-table relationship


【解决方案1】:

尝试从您的模型中删除“group_recipent”。我假设您想知道第一个字段是数据透视表名称。它应该是这样的:

return $this->belongsToMany(Recipent::class)->withPivot('recipent_id', 'group_id');

如果有人有其他想法,请在下面添加评论。

【讨论】:

  • 谢谢!我没有抓住这个。为什么人们不喜欢这个答案? ://
猜你喜欢
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 2017-06-21
  • 2016-11-21
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多