Leff
Leff

Reputation: 1320

Laravel constraining eager loading not working

I am making a query where I would like to check the relationship that I have set up like this:

Content model:

public function contentType()
{
    return $this->belongsTo('App\ContentType', 'ct_id');
}

ContentType

public function contents()
{
    return $this->hasMany('App\Content', 'ct_id');
}

And, then I have tried to do a query like this:

$content = Content::where('slug', $arguments['slug'])
                ->with(['contentType' => function ($query) {
                    $query->where('slug', 'post');
                }])->get();

return $content;

Where I wanted to get $content from the Db, that has the contentType of slug post, and I am getting the content from the table, but after testing it, I am getting the same record every time no matter what I put as a slug for contentType. I only have one record in the Db, that is why I am getting the same record, but I should even get that one, if it doesn't have the contentType that has a slug different than post. What am I doing wrong?

Upvotes: 0

Views: 433

Answers (1)

Leff
Leff

Reputation: 1320

I was able to achieve what I want with whereHas query:

$content = Content::whereHas('contentType', function ($query) {
                    $query->whereIn('slug', ['post', 'page']);
                })
                ->where('slug', $arguments['slug'])
                ->with('supplementary')
                ->first();

That way I fetch only content that has either post or page as a slug in the contentType relationship.

Upvotes: 1

Related Questions