Laravel 4 Eloquent Column Alias

混江龙づ霸主 提交于 2019-11-27 06:16:58

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/17174837/laravel-4-eloquent-column-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!