筛选表,基于另一个表中的字段

时间:2019-03-09 15:37:38

标签: mysql laravel eloquent laravel-query-builder

我为此感到困惑。我有一个包含各个字段的表: $employees。我想这就是您所说的集合,我认为,当我调用该集合时,将返回数据库中的所有员工记录(此示例中为4条记录)

每个员工记录具有以下字段 first_namelast_nameageother_id

还有另一个表(或集合),我称之为过滤器表。它称为$other_ids。它有两个记录,其中包含以下字段-idid_name

我希望能够过滤$employees表,使其仅保留记录,其中other_id等于过滤表中id的两个值之一- $other_ids

例如,如果过滤器表具有以下两个记录:

[{"id":1 "id_name":"one"}, {"id":2, "id_name":"two"}]

$ employee表包含记录:

[{"first_name":"ted", "surname_name":"stark", "age":35, "other_id":1},
{"first_name":"fred", "surname_name":"strange", "age":30, "other_id":2},
{"first_name":"incredible", "surname_name":"hulk", "age":25, "other_id":3},
{"first_name":"captain", "surname_name":"stone", "age":28, "other_id":2}]

过滤之后,它应返回$employees_filtered,只包含记录 1、2和4

我尝试做left-join并使用whereHas和where子句,但没有任何效果!

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找类似-

$otherId = [1, 2];
$employees_filtered = Employee::with('Others')->whereIn('other_id', $otherId)->get();

请不要忘记与他们的模型建立联系。 在Other.php模型中-

public function Employees()
{
    return $this->hasMany('App\Other', 'other_id', 'id');
}

Employee.php模型中-

public function Others()
{
    return $this->belongsTo('App\Employee', 'other_id', 'id');
}
相关问题