Vittore Gravano
Vittore Gravano

Reputation: 766

How to add joined column from nested query

I am trying to add joined column from nested query using whereHas statement like this:

$options = Option::whereHas('texts', function($query) {
        $query->addSelect('options_text.text');
    })->where(['active' => 1, ])
    ->first();

But as result $options->text gives null. Is there any ideas how to do this? Without making all query using ->join().

My model is fine, here is my relation:

public function texts()
{
    return $this->hasMany('App\OptionText', 'option_id', 'id');
}

I use it in different situations and is works correct.

Upvotes: 1

Views: 216

Answers (1)

Namoshek
Namoshek

Reputation: 6544

What you are looking for is the with([$relation => $callback]) notation. Here you can specify that only one column should be loaded:

$options = Option::query()
    ->with(['texts' => function ($query) {
        $query->select(['id', 'text']);
    }])
    ->where('active', 1)
    ->first();

Don't forget to also select the id column (or your key column, if that isn't id) because otherwise, Eloquent doesn't know which related object belongs to which parent.

If you also need a constraint on the related table, you can simply add it to your query:

$options = Option::query()
    ->with(['texts' => function ($query) {
        $query->select(['id', 'text']);
    }])
    ->whereHas('texts', function ($query) {
        $query->where('text', 'LIKE', '%dog%');
    })
    ->where('active', 1)
    ->first();

Upvotes: 2

Related Questions