Harrison
Harrison

Reputation: 2670

How to add relationships for additional columns in pivot table in Laravel and Eloquent?

I have 3 tables:

users
-id
-name

relation_types
-id
-type

user_relation
-user1_id
-user2_id
-relation_type_id

In User model I have:

public function relatedParties()
    {
        return $this->belongsToMany('App\User', 'user_relation', 'user1_id', 'user2_id')->withPivot('relation_type_id');
    }

I can get the relation_type_id by App\User::find(1)->relatedParties[0]->pivot->relation_type_id.

In order to get relation type instead of id, I added this relationship in the model of user_relation table

public function type()
    {
        return $this->belongsTo('App\RelationType', 'relation_type_id');
    }

but App\User::find(1)->relatedParties[0]->pivot->type returns null

Any thoughts would be appreciated.

Upvotes: 1

Views: 1083

Answers (2)

Imran Hossain
Imran Hossain

Reputation: 606

You can't access type from pivot table because type is not a column in the proviot table. so your code for access type is giving null for acessing type.

App\User::find(1)->relatedParties[0]->pivot->type

Again relationship in user_relation table is between relation_types, user_relation table which can not be called in the realtion of users,user_relation.

To get the type of "relation_type_id" just simply get the type from relation_types table as written below.

$relationTypeId = \App\User::find(3)->relatedParties[0]->pivot->relation_type_id;
$rtype = \App\RelationType::find($relationTypeId)->pluck('type');
echo $rtype;

Upvotes: 0

Sanzeeb Aryal
Sanzeeb Aryal

Reputation: 3266

You can use Nested Eager Loading

$user=User::with('relatedParties','relatedParties.type')->first();
foreach($user->relatedParties as $relatedParty)
{
   foreach($relatedParty->type as $type)
   {
         print_r($type->type);
   }
}

Upvotes: 1

Related Questions