【问题标题】:Laravel Eloquent where in relationship may or may not have resultLaravel Eloquent 在关系中可能有也可能没有结果
【发布时间】:2016-11-18 12:19:10
【问题描述】:

我有这个关系:

一个Company 可能有一个或多个Employees

我需要根据Employeefirst_nameSELECT 公司,但当员工的first_name 不匹配时不显示。

这是我目前拥有的。

$companies = Company::with(array('employees' => function($q) {
    $type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
    $q->where( 'employees.first_name', 'LIKE', $type);
}))->get();

如果Company 没有任何Employees,则必须忽略员工first_name

但它会显示公司数据,即使员工不匹配。员工只是被隐藏了。

我将如何继续这样做?

【问题讨论】:

    标签: php laravel-5 eloquent relational-database


    【解决方案1】:

    试试这个方法:

    $companies = Company::whereHas('employees', function($q){
        $type = (!empty(Input::get('company_search_employee'))) ? '%' . Input::get('company_search_employee') . '%' : '%';
        $q->where( 'first_name', 'LIKE', $type);
    })->get();
    

    或者如果它不起作用,则在 where 子句中添加“员工”:

    $q->where('employees.first_name', 'LIKE', $type);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 2021-01-26
      • 1970-01-01
      • 2016-02-25
      • 2015-06-30
      • 1970-01-01
      相关资源
      最近更新 更多