Laravel - Filter a collection by a dynamic field

可紊 提交于 2021-01-29 05:43:53

问题


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);

    }

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


回答1:


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.

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.




回答2:


$collection = VenderModel::get();

$collection->filter(function($item) use($title) {
    return preg_match('/.*'.$title.'.*/', $item->fullTitle) !== false;
});

return response()->json($collection, 200);

I think this should solve it. You can't use query on a field that is not actually field in your table, but you should be able to filter it as a collection



来源:https://stackoverflow.com/questions/57093497/laravel-filter-a-collection-by-a-dynamic-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!