laravel - Laravel - 按动态字段过滤集合
问题描述
该模型有 3 个字段是模型的属性,第 4 个字段是一个动态字段,称为“fullTitle”
[
{
"id": 1,
"hours": 2000,
"car_id": 3,
"fullTitle": "Test",
}
}
<?php
namespace App;
use App\Car;
class VenderModel extends Model
{
use TranslationTrait;
protected $guarded = ['*'];
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = [
'fullTitle'
];
/**
* Accessor for dynamic property fullTitle to use as selector name.
* @param string $locale
* @return null|string|string[]
*/
public function getFullTitleAttribute($locale = 'es')
{
if (null === $this->hasTranslation()) {
return trans('errors.No name');
}
return preg_replace('/\s{2,}/', ' ', $this->code.' '. $this->translationOrFirst($locale)->translation);
}
}
public function index(Request $request): JsonResponse
{
$limit = $request->input('limit', 25);
$title = $request->input('title');
$query = VenderModel::all();
$query->when($request->query('title'), function ($q) use ($title) {
return $q->where('fullTitle', 'like', '%' . $title . '%');
});
return response()->json($query, 200);
}
我想要做的是用 fullTitle 拾取元素但不起作用
解决方案
您不能要求数据库搜索表中实际不存在的内容。
仅当您要求派生属性时才调用自定义属性。它们不能在查询中使用。
或者,您可以获取内存中的所有行,然后使用 PHP 对其进行过滤,但这不是一个好方法。
您也可以考虑将特定属性的翻译存储在相关表中,然后按关系在数据库中搜索。
推荐阅读
- c# - 如何访问添加到面板的控件?
- azure-devops - Azure DevOps:我们能否识别从变更集编号触发的构建?
- c++ - C++ 如何修改文本文件的内容?
- r - 如何在R中的tidyverse中反转分数的分位数?
- javascript - SharePoint Online 未捕获类型错误:无法读取未定义的属性“应用”
- server - 无法在服务器 C++ 中连接第二个客户端
- c# - 如何通过触发器将玩家传送到不同的场景?
- c++ - 如何将 OpenGL 中的东西缩放到实际大小?
- java - Spring Data JPA 乐观锁定与旧版 DB2/400
- python - 我应该为 Python 中的公共装饰方法编写单元测试吗(即@property)