简体   繁体   中英

Laravel - How to query Eloquent relationship?

I have this models in 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',
              ];
}

Then I have this Query in Employee controller function:

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

How do I include where is_active = 1 from employee_types into the query in Employee:

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

You are looking for the whereHas method, querying for the existence of a relationship:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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