princeoo7
1 month ago

how to search result in data appended in model ?

Posted 1 month ago by princeoo7

I have 2 tabled, First is category and second is categoryTrasnlation. As the name suggest. 1st table save based data for a category and the 2nd one save language translation data.

Now this data is always required in every query been made so it made sense for me to directory append this data in Model itself with,

    protected $appends = ['data'];
   
    public function getDataAttribute() {
        return $this->translations()->select(['lang_code', 'title'])->get();
    }

    public function translations() {
        return $this->hasMany(CategoryTranslation::class, 'category_id');
    }

My question is how to search for data from categoryTranslation table as it have the title field where different language title are stored.

currently what I am doing in the controller is as below:

$records = Category::paginate(config('app.rec_limit'));

Normally how I would have done this is as below:

$r = request()->input('s');
                $records = Category::whereHas('translations', function($q) use ($r){
                    return $q->where('title',  'LIKE', '%' . $r . '%');
                })->paginate(env('app.rec_limit'));

Please let me know where am I going wrong...

Please sign in or create an account to participate in this conversation.