polishboy14f4
polishboy14f4

Reputation: 85

Get filtered child from parent

I have a one to many relationship. So I can use this code to display all posts.

$tag = Tag::where('slug', $slug)->first();
$posts = $tag->posts;

It works correctly but I want to filter child to display. For example:

$posts = $tag::whereHas('posts', function($query){
$query->where('accept', 1)
})->get();

But it gets tags not posts. Any idea how I can solve my problem?

Upvotes: 3

Views: 66

Answers (3)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

You can use

$tag = Tag::where('slug', $slug)
    ->with(['posts' => function($q) {
        $q->where('accept', 1);
    }])->first();
$posts = $tag->posts;

Upvotes: 0

Manian Rezaee
Manian Rezaee

Reputation: 1012

In Post model you have to define relation to tag like this

public function tags(){
    return $this->hasMany(Tag::class);
}

and this is how you can get posts from specific tag

$slug = "my-slug";
$posts = Post::whereHas('tags', function($query) use ($slug){
    $query->where('slug', $slug)
})->where('accept', 1)->get();

Upvotes: 3

Script47
Script47

Reputation: 14550

As mentioned by the documentation:

Since all relationships also serve as query builders, you can add further constraints to which comments are retrieved by calling the comments method and continuing to chain conditions onto the query:

$comment = App\Post::find(1)->comments()->where('title', 'foo')->first();

You can change your code to:

$posts = $tag->posts()->where('accept', 1)->get()

You can directly query the relationship.

Upvotes: 1

Related Questions