Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 2 years ago.
0

Something like this?

http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

I don't know if it will work in all cases (like where()).

Last updated 10 years ago.
0

@beaverusiv It won't work in anything db related, but this is probably the way to go.

@sleepless What do you need that for?

0

Hey,

thanks for the answers.

I have two fields in the database. Sometimes only one (network_name) is set and the other (name) is null. "network_name" can not be empty and is never null because it's retrieved by an API. "name" on the other hand can be null but if not, I'd prefer outputting "name" instead of "network_name"

So, this is why I'd like to get network_name AS name if name is null or name AS name if it's not null. This way I can access it with $result->name and still I'd never get a null value.

Edit:

SELECT *, COALESCE(`name`, `network_name`) AS `name` FROM `api_network`

This query would replace "name" with my desired field. Think with newQuery() I could add this as a column to the query, or?

I mean something like this:

public function newQuery()
{
    $query = parent::newQuery();
    ...
}
Last updated 10 years ago.
0

Maybe you could try creating a scope in your model like:

public function scopeSomething($query){
    return $query->addSelect(\DB::raw('COALESCE(`name`, `network_name`)'));
}

Try it and let me know if the problem exists.

0

Thanks, but I did it with an accessor :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

sleepless sleepless Joined 20 Sep 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.