mysql - 雄辩:从 whereHas 块中选择字段失败
问题描述
我使用 , 等的组合得到了一个稍微复杂的where
SQLwhereHas
查询orWhereHas
。
一切顺利,但是当我'custom_records.custom_title'
在 Select 字段中添加(见下文)时,它失败了:
The Response content must be a string or object implementing __toString(), "boolean" given.
有任何想法吗?这是片段:`
$record = $this->record->newQuery();`
$record->whereHas('customRecords', function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$searchTerm.'%');
});
return $record->get([
'records.id',
'records.another_field',
'records.another_field_2',
'custom_records.custom_title',
]);
更新 当我在 mysql 客户端上运行生成的 SQL 查询时,它会返回:
Unknown column 'custom_records.custom_title',' in 'field list'
解决方案
你不能这样选择custom_records.custom_title
。由于它是一种HasMany
关系,因此可以有多个custom_records
per record
。
你必须做这样的事情:
$callback = function ($query) use ($searchTerm) {
$query->where('custom_title', 'like', '%'.$searchTerm.'%');
};
Record::whereHas('customRecords', $callback)
->with(['customRecords' => $callback])
->get(['id', 'another_field', 'another_field_2']);
推荐阅读
- javascript - 在继续之前等待最短时间
- hash - 有没有办法从基本文件和哈希中找到哈希算法?
- excel - 为什么 VBA 中的 .getElementById 返回错误 462?
- c# - 初始化组件抛出异常
- firebase - 奇怪的 Firebase 电子邮件验证
- python - 在 Django 中重新保存模型实例不起作用,但 update() 确实有效
- php - 我在更新产品数量时遇到问题
- javascript - Chrome 扩展 - “无法读取未定义的属性‘onMessage’”
- c++ - 当位域大于基础类型时,MSVC 会抛出错误。符合那个标准吗?
- ruby-on-rails - Leaflet-Rails OSM Ruby on Rails 无法正确呈现