如何在Laravel和Eloquent中为数据透视表中的其他列添加关系


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

我有3个表:

users
-id
-name
relation_types
-id
-type
user_relation
-user1_id
-user2_id
-relation_type_id

User模型中我有:

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

我可以通过App'User::find(1)->relatedParties[0]->pivot->relation_type_id得到relation_type_id

为了得到relation type而不是id,我在user_relation表的模型中添加了这个关系

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

但是App'User::find(1)->relatedParties[0]->pivot->type返回null

可以使用嵌套式动态加载

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

不能从数据透视表访问type,因为type不是表中的列。所以你的访问类型代码给访问类型null

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

user_relation表中的关系是关系类型之间的关系,user_relation表不能在用户关系中调用,user_relation。

要获取"relation_type_id"的类型,只需从relation_types表中获取类型,如下所示。

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