簡體   English   中英

Laravel 通過數據透視表獲取所有數據

[英]Laravel get all data through pivot Table

您好,我在獲取收件人所屬組的名稱時遇到問題。

我為該主題使用了 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');
}

和我的組模型:

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);

嘗試通過數據透視表訪問組的名稱后,出現錯誤:

照亮\\數據庫\\ QueryException SQLSTATE [42S22]:列未找到:1054未知列在'字段列表' group_recipent.group_recipent“(SQL:選擇groups 。*, group_recipentrecipent_idpivot_recipent_idgroup_recipentgroup_idpivot_group_idgroup_recipentgroup_recipent作為pivot_group_recipentgroups內加入group_recipentgroupsid = group_recipentgroup_id其中group_recipentrecipent_id = 4)

我想訪問 Recipent 所屬組的所有名稱,但出現上述錯誤。 你知道如何解決這個問題嗎? :/

嘗試從您的模型中刪除“group_recipent”。 我假設您想知道第一個字段是數據透視表名稱。 它應該是這樣的:

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

如果有人有其他想法,請在下面添加評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM