繁体   English   中英

Laravel - 如何查询 Eloquent 关系?

[英]Laravel - How to query Eloquent relationship?

我在 Laravel-5.8 中有这个模型:

class Employee extends Model
{
    public $timestamps = false;
    protected $table = 'employees';
    protected $primaryKey = 'id';

    protected $fillable = [
                  'id',
                  'first_name',
                  'last_name',
                  'hr_status',      
                  'employee_type_id',
              ];

    public function employeetype()
    {
        return $this->belongsTo('App\Models\Hr\EmployeeType','employee_type_id','id');
    }           
}


class EmployeeType extends Model
{
    public $timestamps = false;
    protected $table = 'employee_types';
    protected $primaryKey = 'id';

    protected $fillable = [
                  'type_name',
                  'is_active',
              ];
}

然后我在员工 controller function 中有这个查询:

 $unsubmitted = Employee::where('hr_status', 0)->get();

如何将employee_types中的is_active = 1包含在Employee中的查询中:

$unsubmitted = Employee::where('hr_status', 0)->get();

您正在寻找whereHas方法,查询是否存在关系:

Employee::where('hr_status', 0)
    ->whereHas('employeetype', function ($q) {
        $q->where('is_active', 1);
    })->get();

Laravel 5.8 Docs - Eloquent - 关系 - 查询关系存在whereHas

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM