本文介绍了Laravel通过数据透视表拥有一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有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通过数据透视表拥有一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 07:32