所以我有2个模型,用户&配置文件,关系设置如下:
So I have 2 models, User & Profile, the relationship is set up as follows:
/** * 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(数据透视表)
I have 3 tables, users, profiles & user_profiles (the pivot table)
我的用户表中有一列称为active_profile,其中填充了配置文件ID.
I have a column in my users table called active_profile which gets populated with a profile id.
如何建立关系,以便可以调用类似以下的内容:
How can I set up the relationship so that I can call something like the following:
$user->active_profile
这样它将返回在active_profile中设置的ID的所有配置文件信息?
So that it will return all the profile information for the id set in active_profile?
推荐答案您可以像这样将方法添加到您的User模型中:
You can add a method into your User model like this :
public function active_profile () { return $this->profiles() ->find($this->active_profile); }然后可以将该方法调用为$ user-> active_profile();
and then you can call the method as $user->active_profile();
更多推荐
Laravel通过数据透视表拥有一个
发布评论