我正在使用典型的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%)
感谢任何帮助。
答案 0 :(得分:3)
您收到该错误的原因是,当查询实际位于fulllocation
表中时,查询正在查找帐户表中的zipcodes
。
您可以尝试以下方式:
$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
希望这有帮助!