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()).
@beaverusiv It won't work in anything db related, but this is probably the way to go.
@sleepless What do you need that for?
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();
...
}
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community