【发布时间】: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 @ aspivot_group_id,group_recipent.group_recipentaspivot_group_recipentfromgroupsinner joingroup_recipentongroups.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