【发布时间】: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