kalview
kalview

Reputation: 360

Laravel get all data through pivot Table

Hello I've got problem with getting the name of Group which Recipent is member.

I use 3 tables for that subject : recipent, group and group_recipent.

In group_recipent table I've got only columns like recipent_id and group_id. All is correct to Laravel naming convention.

It's my Recipent model:

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

And my Group model:

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

Accessing data:

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

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

After trying to access the name of a group through pivot table I get an error:

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)

I wanted to acces the name all names of group which recipent is member of but I get error like above. Have you any idea how to solve that? :/

Upvotes: 2

Views: 2733

Answers (1)

wpcpremium80
wpcpremium80

Reputation: 98

Try to delete from your models 'group_recipent'. I assume you're wonder that the 1st field is pivot table name. It should look like this:

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

If someone got other idea, just add comment below.

Upvotes: 2

Related Questions