vendredi 13 décembre 2019

How to use the relations in Eloquent Filters for search

I have story table and tag table. Story table has a relational table storytag and other relational table storytagitem. In storytag the id of stories are there and in storytagitem the id of storytag and the id of tags are there. Its may be clear about database relationships.

so i am using the search filter. here is the endpoint: http://127.0.0.1:8000/admin/stories?tags=10

output is here:

{
    "data": [
        {
            "id": 3939,
            "title": "My Life",
            "image": "123.jpg",
            "views": 20,
            "likes": 0,
            "url_key": "--b5466c",
            "language": "english",
            "public": true,
            "status": "published",
            "published_date": "11 Nov, 2019",
            "published_difference": "1 month before",
            "tags": [
                {
                    "id": 10,
                    "label": "Poetry",
                    "value": "poetry",
                    "image": "http://127.0.0.1:8000/tags/November2019/cOgppZ1FNW7PNHdUnH3Z.jpeg",
                    "count": 175,
                    "type": "normal"
                }

Here is my StoryFilter for tags.

    public function tags($term) 
    {
        return $this->builder->whereHas('tags', function ($query) use ($term) {
            return $query->where('tag_id', 'LIKE', "%$term%");
        });
    }

I want the endpoint is something like with the tag lable. http://127.0.0.1:8000/admin/stories?tags=Poetry

The StoryModel with relation with StoryTag

    public function storyTags()
    {
        return $this->hasOne('App\Model\StoryTag');
    }

    public function tags()
    {
        return $this->hasManyThrough('App\Model\StoryTagItem', 'App\Model\StoryTag');
    }

Here is the StoryTagItem Model relation with StoryTag

    public function tags()
    {
        return $this->belongsTo('App\Model\StoryTag');
    }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire