framework icon indicating copy to clipboard operation
framework copied to clipboard

"addSelect" override relationship selects

Open simplenotezy opened this issue 12 years ago • 13 comments

I want to fetch a model and its relationship.

I can get this to work successfully, but when I add ->addSelect('last_read'); (stored from the pivot table), the conversations.* select is gone. The only workaround is to do: ->select('conversations.*')->addSelect('last_read')

Example:

$conversations = $this->user->conversations()->with([
'messages' => function($messages) {
    /**
     * Get last five messages from conversation
     */

        $messages->limit(5);
        $messages->orderBy('created_at', 'DESC');
}])->get();

Generates:

 select `conversations`.*, `conversation_user`.`user_id` as `pivot_user_id`, `conversation_user`.`conversation_id` as `pivot_conversation_id` from `conversations` inner join `conversation_user` on `conversations`.`id` = `conversation_user`.`conversation_id` where `conversation_user`.`user_id` = '1'

But when I append addSelect, it looks like this:

 select `last_read`, `conversation_user`.`user_id` as `pivot_user_id`, `conversation_user`.`conversation_id` as `pivot_conversation_id` from `conversations` inner join `conversation_user` on `conversations`.`id` = `conversation_user`.`conversation_id` where `conversation_user`.`user_id` = '1'

Is this me misunderstanding something, or is it a bug?

simplenotezy avatar Nov 27 '14 12:11 simplenotezy

Same problem here.

Trying this in my model:

public function newQuery()
{
    $query = parent::newQuery()->addSelect('name');

    return $query;
}

It's simply replacing the previous columns with "name" and not adding anything...

sleepless avatar Dec 18 '14 03:12 sleepless

I'm retrying with @rkgrep's fix, since there is nothing wrong with it - CI passes and it works as intended.

DusanKasan avatar Mar 18 '15 12:03 DusanKasan

According to @taylorotwell (https://github.com/laravel/framework/pull/8048), current state is correct. This issue can be closed.

DusanKasan avatar Mar 18 '15 15:03 DusanKasan

Could somebody explain why above can be the expected behavior?

simplenotezy avatar Mar 18 '15 16:03 simplenotezy

Because @taylorotwell thinks you should use select() and fight through an insurmountable id mismatch error, or forego using the ORM at all.

alanondra avatar Jul 14 '16 20:07 alanondra

This issue isn't even very readable. I don't even know what the issue is at all.

The OP talks about something being stored on a pivot table and wanting to access that. If that's the case you shouldn't be using addSelect at all. Instead you should be using ->withPivot('last_read') in your relationship definition.

taylorotwell avatar Jul 14 '16 20:07 taylorotwell

If there is a problem that someone wants fixed it will need to be summarized much better than this.

taylorotwell avatar Jul 14 '16 20:07 taylorotwell

If anyone ends up here, this is what I did from inside one of my scopes.

// Param binding & lateral join don't work together, but id is validated in request so I used str interpolation
$optionIds = collect($selectedOptions)->pluck('id')->join(',');

$query->select($query->columns ?? '*')
    ->addSelect('option_by_options.count')
    ->join(DB::raw("
        LATERAL option_by_options(array[{$optionIds}], {$category->id}) as option_by_options
    "), function (JoinClause $query) {
        $query->whereColumn('option_by_options.id', 'options.id');
    });

If you know a way to bind variables in my join up there please let me know, Im tired.

hexatex avatar Mar 13 '20 02:03 hexatex

same problem with using addSelect in scopes. if anyone wants to reproduce it in latest version:

    public function scopeFoo($query)
    {
        // return $query->addSelect(\DB::raw("1 as foo")); //only returns foo field
        return $query->addSelect(\DB::raw("* , 1 as foo")); //returns foo as well as other fields
    }

yeknava avatar Oct 28 '20 10:10 yeknava

Still not fixed.

cowera avatar Mar 12 '22 13:03 cowera

I put select before adding addSelect() and it works!

MohammedElattar avatar Jun 17 '23 21:06 MohammedElattar

same problem with using addSelect in scopes. if anyone wants to reproduce it in latest version:

    public function scopeFoo($query)
    {
        // return $query->addSelect(\DB::raw("1 as foo")); //only returns foo field
        return $query->addSelect(\DB::raw("* , 1 as foo")); //returns foo as well as other fields
    }

This should only be done if $query->getQuery()->columns is null, otherwise it should be merged $query->getQuery()->columns and your addSelect.

narkoze avatar Sep 13 '23 06:09 narkoze

If someone is also experiencing issues with ->subSelect() expecting an added subquery, where the table.* is missing? When passing a string as subquery, the QueryBuilder thinks it is a column, thereby removing the table.*. Adding a macro that keeps the normal SELECT table.* makes it work for me.

Maybe this will make it work:

// add to a boot method in a ServiceProvider:
Builder::macro('selectSubWithTable', function ($query, $as)
{
    if(is_null($this->columns))
        $this->select($this->from.'.*');

    [$query, $bindings] = $this->createSub($query);

    return $this->selectRaw(
        '('.$query.') as '.$this->grammar->wrap($as), $bindings
    );
});

instead of $query->subSelect("SELECT something FROM table", as: 'somethingFromTable') use: $query->selectSubWithTable("SELECT something FROM table", as: 'somethingFromTable')

I'm not sure if it is an issue/bug or a feature. But this macro makes it acceptable for me. I wouldn't mind if $query->subSelect() could accept a DB:raw-expression to make custom subquery - without changing current select/colums - a possibility.

rvzug avatar Jul 18 '24 21:07 rvzug