Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Eloquent Column Alias

What i am trying to achieve is in my database i have a table named channel i am using laravel's eloquent class to access these the properties from the table The problem that i am facing is that

the table name is column and the column name is channel

so when accessing that property looks like this.

User::find(1)->channel->channel

How can i modify this to say

User::find(1)->channel->name

We cannot change the table name in the database.

Options i have thought of:

1)Create views for tables that need columns changed. Too messy...

2)Use column alias.... laravel documentation...sigh.. no clue how?

3)Use a property set with the create_function that would call this->channel but i am pretty sure it won't work because laravel is using dynamic properties. and when it's fill out in the array im pretty sure it changes it to the name of the column.

I could in my belongs_to/hasOne/hasMany function change the property to the alias of the name i want to use so that later on i can change it. i dunno how well that would work..

any thoughts? much appreciated

like image 293
Lpc_dark Avatar asked Jun 18 '13 17:06

Lpc_dark


People also ask

How to alias column name in Laravel?

When querying an eloquent model, you can alias / change the name of the selected column before returning it to the front-end. To do so you can make use of the "as" keyword within the "select" method. $user = User::select(['id', 'name as nickname'])->first();

How to set alias in Laravel Eloquent?

Animal::select('size','color')->get(); If you're like me and like to use select statements to return specific columns. You'll be happy to know that Eloquent allow you to use select column as alias just like in SQL.

What is aliases in laravel?

Bash aliases are shortcuts added to a file that allows you to reference another command through more memorable words, abbreviations, or characters.

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.


1 Answers

You could probably do it easily with Accessors / Mutators.

class Channel extends Eloquent {

    public function getNameAttribute()
    {
        return $this->attributes['channel'];
    }

    public function setNameAttribute($value)
    {
        $this->attributes['channel'] = $value;
    }

}

Reference

  • Laravel Accessors & Mutators
like image 199
Alexandre Danault Avatar answered Nov 15 '22 02:11

Alexandre Danault