sleepless
sleepless

Reputation: 1789

Laravel: How to add a column to a query?

I need you help. I'm trying to add a column to each query of an specific eloquent model.

Basically I want to add this:

COALESCE(name, network_name) AS name

It's important to keep the previously selected fields so I tried this in my model:

public function newQuery()
{
    $query = parent::newQuery()->addSelect('name'); // it's name only for testing purposes

    return $query;
}

But this doesn't add the column. It replaces it. So instead of getting something like:

select *, name from programs where programs.id = ? limit 1

I get:

select name from programs where programs.id = ? limit 1

What am I doing wrong? I haven't found anything on the net so I really hope you can help me!

Upvotes: 0

Views: 3534

Answers (1)

Mysteryos
Mysteryos

Reputation: 5791

As suggested by prady00, you'll have to implement a function in your Eloquent Model as such:

public static function getMore()
{
     return self::select('*',DB:Raw('COALESCE(name, network_name) AS coalesce_name'))->get();
}

OR

Implement an Accessor:

protected $appends = array('coalescename');

public function getCoalescenameAttribute()
{
    return ($this->name !== '' ? $this->name : $this->network_name);
}

I'll go with the accessor implementation by preference.

Upvotes: 4

Related Questions