【问题标题】:Laravel eager loading and LIKE filterLaravel 急切加载和 LIKE 过滤器
【发布时间】:2017-02-07 10:40:18
【问题描述】:

我正在处理一个典型的 Account->Zipcode 场景。我有 2 个模型 2:帐户和邮政编码,在帐户中我添加了

public function zipcode() {
    return $this->belongsTo(Zipcode::class);
}

index.blade.php 是这样的:

<td>{{$account->id}}</td>
  <td>{{$account->fullname}}</td>
  <td>{{$account->address}}</td>
  <td>{{$account->zipcode->fulllocation}}</td>
...

我为 accounts.fullname 中包含的字符串添加了一个过滤器(列表顶部的基本输入文本),因此控制器如下所示:

public function index(Request $request)
 {
   $search = $request->search;
   //The instructions in the closure given to when() will only be applied if the first argument is evaluated to true
   $accounts = Account::with('zipcode')//https://laravel.com/docs/4.2/eloquent#eager-loading
                  ->when($search,function ($query) use ($search) {
                     $query->where('fullname','like','%'.$search.'%');
                     return $query;
                    })
                  ->latest()
                  ->paginate(15);
     return view('accounts.index', compact('accounts'))->with('search',$search);
 }

此时该场景已测试并正常运行,如果未插入搜索,则会列出所有帐户,否则将正确过滤结果。

我需要在 accounts.fullname 或 accounts.zipcode.fulllocation 中搜索插入的字符串。我尝试以这种方式修改 控制器:

$accounts = Account::with('zipcode')//https://laravel.com/docs/4.2/eloquent#eager-loading
    ->when($search,function ($query) use ($search) {
              $query->where('fullname','like','%'.$search.'%');

              $query->orWhere('fulllocation','like','%'.$search.'%');//ADDED THIS

              return $query;
           })
    ->latest()
    ->paginate(15);

当我尝试时,会出现此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'fulllocation' in 'where clause' (SQL: select count(*) as aggregate from `accounts` where `fullname` like %foo% or `fulllocation` like %foo%)

感谢任何形式的帮助。

【问题讨论】:

    标签: laravel eloquent eager-loading


    【解决方案1】:

    您收到该错误的原因是,查询实际上在 zipcodes 表中查找帐户表中的 fulllocation。

    你可以试试这样的:

    $query->where('fullname', 'like', '%' . $search . '%')
        ->orWhereHas('zipcode', function ($q) use ($search) {
            $q->where('fulllocation', 'like', '%' . $search . '%');
        });
    

    https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence

    希望这会有所帮助!

    【讨论】:

    • 这正是我需要和正在寻找的。实际上我开始配置基于 MySql 表的 Account 模型和基于 Oracle 表的 Zipcode 模型。应用您的解决方案会引发错误,因为查询未找到 mysqlschema.zipcode。目前不需要这么复杂,所以我将所有内容都移到了 mysql 上,它可以正常工作(在 Laravel 方面没有任何变化)。我保留此案例以供进一步研究。
    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2014-08-13
    • 2021-04-23
    • 2018-10-15
    相关资源
    最近更新 更多