Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

php - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...