Laravel-通过动态字段过滤集合 [英] Laravel - Filter a collection by a dynamic field

查看:29
本文介绍了Laravel-通过动态字段过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该模型有3个字段,它们是模型的属性,第4个字段是动态字段,称为"fullTitle"

The model has 3 fields that are attributes of the model and the 4th field is a dynamic field that is called "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拾取元素,但是不起作用

What I'm trying to do is pick up the elements with the fullTitle but doesnt work

推荐答案

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

You cannot ask your database to search for something that does not actually exist in the table.

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

Custom attributes are only called when you ask for the derived property. They cannot be used in the query.

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

Alternatively, you can grab ALL the rows in memory and then filter it with PHP, but it's not a good way.

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

Also you can think about storing translation of specific property in related table and then search in database by relation.

这篇关于Laravel-通过动态字段过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆