2017-02-03 55 views
1

因此,我已2种型号,用户&资料,该关系被设置为如下:Laravel hasOne

/** 
    * User belongs to many Profile 
    * 
    * @return \Illuminate\Database\Eloquent\Relations\belongsToMany 
    */ 
    public function profiles() 
    { 
     return $this->belongsToMany('App\Models\Profile', 'user_profiles'); 
    } 

我有3个表,用户简档& user_profiles(透视表)

我在我的用户表中有一个名为active_profile的列,它填充了一个配置文件ID。

我如何建立关系,以便我可以调用类似如下:

$user->active_profile

,这样它会返回所有的资料信息在active_profile设定的ID?

+0

以下其中一条帖子是否回答你的问题? –

回答

0

您可以添加一个方法的资源为你的User模式是这样的:

public function active_profile() 
{ 
    return $this->profiles() 
      ->find($this->active_profile); 
} 

,然后你可以调用方法,$用户 - > active_profile();

0

你应该能够抢到使用find

$user->profiles()->find($user->active_profile); 
+0

虽然这有效,但我希望有一个更优雅的解决方案,最好使用雄辩的关系。 我将暂时实施您的解决方案,但想暂时将问题留给其他选项。 – ChrisBratherton

1

我可能是错的,但为什么不只是使用belongsTo关系?

public function active_profile() 
{ 
    return $this->belongsTo('App\Models\Profile', 'active_profile'); 
} 

希望这有助于!