我有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;