dtysql0586 2017-06-02 18:02
浏览 39
已采纳

Laravel查询多个相关模型

For example: I have these models in my application. User, Profile, Interest.

I linked the users table with the profiles table by adding the user_id column in the profiles table. And I linked profiles and interests by using a pivot table (interest_profile), Which is (as obvious) will have two columns (profile_id, interest_id).

However, I want to query the users who are associated with a profile, too see who is associated with a particular interest, In other words: "select all users who are having (in their profiles) that particular interest".

I know that I can do this with raw SQL by joining the four tables and then use (where clause).. But I want to do it the Laravel way.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dshnx48866 2017-06-02 18:12
    关注

    First make sure you have your relationships setup correctly on your models like:

    class User extends Model
    {
        public function profile()
        {
            return $this->hasOne(Profile::class);
        }
    }
    
    class Profile extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    
        public function interests()
        {
            return $this->belongsToMany(Interest::class, 'interest_profile');
        }
    }
    
    class Interest extends Model
    {
        public function profiles()
        {
            return $this->belongsToMany(Profile::class, 'interest_profile');
        }
    }
    

    Then you can use whereHas() to constrain a query by a related model and dot notation for nested relations. So your query would be:

    User::whereHas('profile.interests', function($query) use ($interestName) {
        return $query->where('name', $interestName);
    })->get();
    

    That would just return a collection of users. If you wanted to return their profiles and interests as well you would use with():

    User::whereHas('profile.interests', function($query) use ($interestName) {
        return $query->where('name', $interestName);
    })
    ->with('profile.interests')
    ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加