Laravel 4 Eloquent 列别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17174837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 Eloquent Column Alias
提问by Lpc_dark
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
我想要实现的是在我的数据库中我有一个名为 channel 的表我正在使用 laravel 的 eloquent 类来访问这些表中的属性我面临的问题是
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...
1)为需要更改列的表创建视图。太乱了...
2)Use column alias.... laravel documentation...sigh.. no clue how?
2)使用列别名....laravel 文档...叹息...不知道如何?
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.
3)使用带有 create_function 的属性集会调用 this->channel 但我很确定它不会工作,因为 laravel 正在使用动态属性。当它在数组中填写时,我很确定它将它更改为列的名称。
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..
我可以在我的belongs_to/hasOne/hasMany 函数中将属性更改为我想要使用的名称的别名,以便稍后我可以更改它。我不知道那会有多好..
any thoughts? much appreciated
有什么想法吗?非常感激
回答by Alexandre Danault
You could probably do it easily with Accessors / Mutators.
您可能可以使用 Accessors / Mutators 轻松完成。
class Channel extends Eloquent {
public function getNameAttribute()
{
return $this->attributes['channel'];
}
public function setNameAttribute($value)
{
$this->attributes['channel'] = $value;
}
}