【问题标题】:Laravel 5 get row from relationship modelLaravel 5 从关系模型中获取行
【发布时间】:2015-12-05 15:51:59
【问题描述】:

我有以下关系模型设置:

  • 用户
  • 用户可以拥有多个职位
  • 用户可以有多种员工类型

    <?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();
        }
    }
    

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

我尝试过这样的事情,但没有这样的运气!请问有人能告诉我这是怎么可能的吗?

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

上面的代码给出了错误:

调用未定义的方法 Illuminate\Database\Query\Builder::jobTitles()

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    使用eager loading:

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

    您只能直接从模型中调用关系,这就是您尝试失败的原因(whereIn() 返回Builder)。

    急切/嵌套加载是在遍历多个模型及其关系之前获取数据的非常有效的方法(否则您最终可能会遇到大量数据库查询);)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-19
      • 2016-05-26
      • 2017-01-12
      • 2023-04-06
      • 2016-08-20
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      相关资源
      最近更新 更多