dongxi4235 2017-02-03 22:07
浏览 81
已采纳

Laravel有一个通过数据透视表

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');
    }

I have 3 tables, users, profiles & user_profiles (the pivot table)

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

So that it will return all the profile information for the id set in active_profile?

  • 写回答

5条回答 默认 最新

  • duananyantan04633 2017-02-03 22:29
    关注

    You can add a method into your User model like this :

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

    and then you can call the method as $user->active_profile();

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog