首页 > 解决方案 > 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 拾取元素但不起作用

标签: laravellaravel-5eloquent

解决方案


您不能要求数据库搜索表中实际不存在的内容。

仅当您要求派生属性时才调用自定义属性。它们不能在查询中使用。

或者,您可以获取内存中的所有行,然后使用 PHP 对其进行过滤,但这不是一个好方法。

您也可以考虑将特定属性的翻译存储在相关表中,然后按关系在数据库中搜索。


推荐阅读