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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?