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',
];
}
然后我在员工控制器函数中有这个查询:
$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 - Relationships - Querying Relationship Existence whereHas
我在 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',
];
}
然后我在员工控制器函数中有这个查询:
$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 - Relationships - Querying Relationship Existence whereHas