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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀