问题描述
我想要实现的是在我的数据库中我有一个名为 channel 的表我正在使用 laravel 的 eloquent 类来访问表中的这些属性我面临的问题是
What i am trying to achieve is in my database i have a table named channeli am using laravel's eloquent class to access these the properties from the tableThe problem that i am facing is that
表名为列,列名为通道
所以当访问该属性时看起来像这样.
so when accessing that property looks like this.
User::find(1)->channel->channel
我该如何修改这个说法
User::find(1)->channel->name
我们无法更改数据库中的表名.
We cannot change the table name in the database.
我想到的选项:
1)为需要更改列的表创建视图.太乱了...
1)Create views for tables that need columns changed. Too messy...
2) 使用列别名....laravel 文档...唉...不知道怎么做?
2)Use column alias.... laravel documentation...sigh.. no clue how?
3) 使用带有 create_function 的属性集来调用 this->channel但我很确定它不会工作,因为 laravel 正在使用动态属性.当它在数组中填写时,我很确定它会将其更改为列的名称.
3)Use a property set with the create_function that would call this->channelbut 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.
我可以在我的belongs_to/hasOne/hasMany 函数中将属性更改为我想要使用的名称的别名,以便稍后我可以更改它.我不知道那效果如何..
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
推荐答案
您可能可以使用 Accessors/Mutators 轻松完成.
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;
}
}
参考
- Laravel Accessors &突变体
这篇关于Laravel 4 Eloquent 列别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!