Laravel 通过 pivot 获取所有数据 Table
Laravel get all data through pivot Table
您好,我在获取 Repent 所属组的名称时遇到了问题。
我为该主题使用了 3 tables:recipent、group 和 group_recipent。
在 group_recipent table 中,我只有 recipent_id 和 group_id 这样的列。一切都符合 Laravel 命名约定。
这是我的 Recient 型号:
public function groups()
{
return $this->belongsToMany(Group::class)->withPivot('group_recipent', 'recipent_id', 'group_id');
}
我的群组模型:
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);
尝试通过 pivot table 访问组名称后,我收到错误消息:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'group_recipent.group_recipent' in 'field list' (SQL: select groups
.*, group_recipent
.recipent_id
as pivot_recipent_id
, group_recipent
.group_id
as pivot_group_id
, group_recipent
.group_recipent
as pivot_group_recipent
from groups
inner join group_recipent
on groups
.id
= group_recipent
.group_id
where group_recipent
.recipent_id
= 4)
我想访问 recipent 所属组的所有名称,但出现如上所示的错误。你知道如何解决吗? :/
尝试从您的模型中删除 'group_recipent'。我假设你想知道第一个字段是 pivot table name。它应该是这样的:
return $this->belongsToMany(Recipent::class)->withPivot('recipent_id', 'group_id');
如果有人有其他想法,请在下面添加评论。
您好,我在获取 Repent 所属组的名称时遇到了问题。
我为该主题使用了 3 tables:recipent、group 和 group_recipent。
在 group_recipent table 中,我只有 recipent_id 和 group_id 这样的列。一切都符合 Laravel 命名约定。
这是我的 Recient 型号:
public function groups()
{
return $this->belongsToMany(Group::class)->withPivot('group_recipent', 'recipent_id', 'group_id');
}
我的群组模型:
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);
尝试通过 pivot table 访问组名称后,我收到错误消息:
Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column 'group_recipent.group_recipent' in 'field list' (SQL: select
groups
.*,group_recipent
.recipent_id
aspivot_recipent_id
,group_recipent
.group_id
aspivot_group_id
,group_recipent
.group_recipent
aspivot_group_recipent
fromgroups
inner joingroup_recipent
ongroups
.id
=group_recipent
.group_id
wheregroup_recipent
.recipent_id
= 4)
我想访问 recipent 所属组的所有名称,但出现如上所示的错误。你知道如何解决吗? :/
尝试从您的模型中删除 'group_recipent'。我假设你想知道第一个字段是 pivot table name。它应该是这样的:
return $this->belongsToMany(Recipent::class)->withPivot('recipent_id', 'group_id');
如果有人有其他想法,请在下面添加评论。