dtysql0586 2017-06-02 10: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 10: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部