Lucid - how to filter results based on value of related data

#1

I have a posts model with a has many relation to tags

If a user clicks a tag in the UI I want to return the posts which have that tag. The examples given in the docs seem to show how I can filter the tags that I want to bring back with every post, but not how to limit the posts results themselves based on a tag being present.

0 Likes

#2

I have tried to understand your question, so I hope to be helpful with this answer

I mean if you want to select all posts related to a tag, I guess you need to have a

hasMany relationship


//Post Model

class Post extends Model
{
    tags() {
        return this.hasMany('App/Models/Tag')
   }
}

Now a belongsTo() relationship



//Tag model
class Tag extends Model
{
      post() {
         return this.belongsTo('App/Models/Post')
     }
}

Maybe with a query like this


const postsRelated = await Tag.query().with('post').fetch()

And now to show them in this way


@each(element in postsRelated)
       {{ element.post.title }}
       {{ element.nameTag }}
@endeach

1 Like

#3

Thanks @ShadowPaz , of course I just need to turn the query on it’s head. Sometimes you can’t see the wood for the trees when you are staring at the screen all day. I was using

Post.query().with('tag', (builder)=>{ builder.where(.....)})

Thanks again.

1 Like