首页 文章

laravel雄辩的关系查询

提问于
浏览
0

我有两张 table
1)用户{id,密码}
2)专业知识{id,expertise}

我的关系是

Models

Expertise.php

function User()
{

  $this->hasOne('Expertise');

}

user.php的

function Expertise()
 {
  $this->hasOne('User');

 }

那么如何使用Eloquent查询前10位具有一定专业知识的用户呢?我想加入users.id = expertise.id并获得具有指定专业知识的前10个人(Where子句) .

初学者到拉拉维尔,我检查了其他来源,但没有成功

1 回答

  • 3

    目前,您对数据建模方式存在问题 . 如果你有一对一的关系,那么建模它的最佳做法是让一个实体存储另一个实体的id . Laravel的惯例是有一个名为 <model>_id 的列:

    Users
    | id | password |
    
    Expertises
    | id | expertise | user_id |
    

    然后在你的模型中你可以这样做:

    型号

    Expertise.php

    class Expertise extends Eloquent
    {
    
        public function User()
        {
              // because expertise has a column user_id
              // expertise belongs to user
              return $this->belongsTo('User');
        }
    
    }
    

    user.php的

    class User extends Eloquent
    {
    
         public function Expertise()
         {
              // because expertise is the one with the column 
              // user_id, user has one expertise
              return $this->hasOne('Expertise');
         }
    }
    

    查询

    完成所有这些设置后,为了能够查询具有特定专业知识的前10位用户,您可以执行此操作 .

    $users = User::whereHas('Expertise', function($q)
             {
                   $q->where('expertise', '=', <expertise you are looking for>)
             })
              ->take(10)
              ->get();
    

    要进一步阅读Laravel中的查询关系,请查看以下内容:

    Laravel - Querying Relationships

    请记住

    请记住,表名必须是复数,否则你应该在模型中指定表的名称:

    protected $table = 'expertise';
    

相关问题