首页 > 解决方案 > 雄辩:从 whereHas 块中选择字段失败

问题描述

我使用 , 等的组合得到了一个稍微复杂的whereSQLwhereHas查询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'

标签: mysqllaraveleloquent

解决方案


你不能这样选择custom_records.custom_title。由于它是一种HasMany关系,因此可以有多个custom_recordsper 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']);

推荐阅读