2015-12-05 54 views
0

我有以下关系模式设置:Laravel 5 GET行

  • 用户
  • 用户可以有许多职称
  • 用户可以有很多员工类型

    <?php 
    
    namespace App\Models\User; 
    
    use Illuminate\Auth\Authenticatable; 
    use Illuminate\Database\Eloquent\Model; 
    use Illuminate\Auth\Passwords\CanResetPassword; 
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; 
    use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; 
    
    class User extends Model implements AuthenticatableContract, CanResetPasswordContract 
    { 
        use Authenticatable, CanResetPassword; 
    
        /** 
        * The database table used by the model. 
        * 
        * @var string 
        */ 
        protected $table = 'user'; 
    
        /** 
        * The attributes that are mass assignable. 
        * 
        * @var array 
        */ 
        protected $fillable = ['first_name', 'last_name', 'email', 'status', 'activation_code']; 
    
        /** 
        * The attributes excluded from the model's JSON form. 
        * 
        * @var array 
        */ 
        protected $hidden = ['password', 'remember_token', 'activation_code']; 
    
        /** 
        * The roles that belong to the user. 
        * 
        * @return Object 
        */ 
        public function roles() 
        { 
         return $this->belongsToMany('App\Models\User\Role')->withTimestamps(); 
        } 
    
        /** 
        * The employee types that belong to the user. 
        * 
        * @return Object 
        */ 
        public function employeeTypes() 
        { 
         return $this->belongsToMany('App\Models\User\EmployeeType')->withTimestamps(); 
        } 
    
        /** 
        * The job itles that belong to the user. 
        * 
        * @return Object 
        */ 
        public function jobTitles() 
        { 
         return $this->belongsToMany('App\Models\User\JobTitle')->withTimestamps(); 
        } 
    } 
    

现在,我希望能够选择用户列表和他们的所有职位s和员工类型。

我已经尝试过这样没有这种运气的东西!请有人建议如何这是可能的?

$this->user->whereIn('id', $ids)->jobTitles()->get(); 

上面的代码提供了错误:

Call to undefined method Illuminate\Database\Query\Builder::jobTitles()

回答

3

使用eager loading

$this->user->whereIn('id', $ids)->with('jobTitles', 'employeeTypes')->get(); 

您只能从模型直接调用的关系,这就是为什么你的尝试失败(whereIn()回报Builder )。

在通过多个模型及其关系循环之前取数据的非常有效的方法是非常有效的方法(否则您可能会有很多db查询);)