【问题标题】:Laravel querying multiple related modelsLaravel 查询多个相关模型
【发布时间】:2017-11-04 05:15:05
【问题描述】:

例如:我的应用程序中有这些模型。 User, Profile, Interest.

我通过在profiles 表中添加user_id 列将users 表与profiles 表关联起来。我使用数据透视表 (@​​987654330@) 链接了 profiles 和 interests,这(很明显)将有两列(profile_id,interest_id)。

但是,我想查询与个人资料相关联的用户,也想查看与特定兴趣相关联的用户,换句话说:“选择所有(在他们的个人资料中)具有特定兴趣的用户”。

我知道我可以通过连接四个表然后使用(where 子句)来使用原始 SQL 来做到这一点。但我想用 Laravel 的方式来做。

提前致谢。

【问题讨论】:

    标签: php laravel orm eloquent query-builder


    【解决方案1】:

    首先确保您在模型上正确设置了关系,例如:

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

    然后您可以使用whereHas() 通过相关模型和嵌套关系的点表示法来约束查询。所以你的查询是:

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

    这只会返回一组用户。如果您还想返回他们的个人资料和兴趣,您可以使用with():

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

    【讨论】:

      【解决方案2】:

      假设User 模型具有profile 关系,而Profile 模型具有interests 关系,您可以这样做。

      $interest_id = 1;
      
      $users = User::whereHas('profile', function ($query) use ($interest_id) {
          $query->whereHas('interests', function ($query) use ($interest_id) {
              $query->where('id', $interest_id);
          });
      })->get();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 2013-05-25
        • 2014-01-18
        相关资源
        最近更新 更多