【问题标题】:Filter Table, based on field in another table过滤表,基于另一个表中的字段
【发布时间】:2023-03-18 01:45:02
【问题描述】:

我对此感到困惑。我有一个包含各种字段的表: $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-joinwhereHas 以及 where 子句,但没有任何效果!

【问题讨论】:

    标签: mysql laravel eloquent laravel-query-builder


    【解决方案1】:

    我认为您正在寻找类似的东西 -

    $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');
    }
    

    【讨论】:

    • 谢谢!模型中的关系已经建立。其中的函数就像一个魅力!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2016-07-14
    • 1970-01-01
    • 2022-12-14
    相关资源
    最近更新 更多