php 如何始终将属性附加到 Laravel Eloquent 模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35701538/
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
How to always append attributes to Laravel Eloquent model?
提问by Mustafa Dwekat
I was wondering how to always append some data to Eloquent model without the need of asking for it for example when getting Posts form database I want to append the user info for each user as:
我想知道如何总是将一些数据附加到 Eloquent 模型而不需要例如在获取 Posts 表单数据库时我想为每个用户附加用户信息:
{
id: 1
title: "My Post Title"
body: "Some text"
created_at: "2-28-2016"
user:{
id: 1,
name: "john smith",
email: "[email protected]"
}
}
回答by Mustafa Dwekat
After some search I found that you simply need to add the attribute you wants to the $appends
array in your Eloquent Model:
经过一番搜索,我发现您只需要将所需的属性添加到$appends
Eloquent 模型中的数组中:
protected $appends = ['user'];
Update:If the attribute exists in the database you can just use
protected $with= ['user'];
according to David Barker'scomment below
更新:如果该属性存在于数据库中,您可以
protected $with= ['user'];
根据下面大卫巴克的评论使用
Then create an Accessor as:
然后创建一个访问器:
public function getUserAttribute()
{
return $this->user();
}
This way you always will have the user object for each post available as:
通过这种方式,您始终可以将每个帖子的用户对象提供为:
{
id: 1
title: "My Post Title"
body: "Some text"
created_at: "2-28-2016"
user:{
id: 1,
name: "john smith",
email: "[email protected]"
}
}
回答by Hemant Kumar
I found this concept is interesting, I learn and share things. Here in this example, I append id_hash variable which then converted into method by this logic, It takes first char and converts into upper case i.e. Id and letter after underscore to uppercase i.e. Hash.
我发现这个概念很有趣,我学习和分享东西。在这个例子中,我附加了 id_hash 变量,然后通过这个逻辑转换为方法,它接受第一个字符并转换为大写,即 Id 和下划线后的字母为大写,即哈希。
Laravel itself add getand Attributeto combine all together it gives getIdHashAttribute()
Laravel 本身添加了get和Attribute来将它提供的所有内容组合在一起 getIdHashAttribute()
class ProductDetail extends Model
{
protected $fillable = ['product_id','attributes','discount','stock','price','images'];
protected $appends = ['id_hash'];
public function productInfo()
{
return $this->hasOne('App\Product','id','product_id');
}
public function getIdHashAttribute(){
return Crypt::encrypt($this->product_id);
}
}
To simplify things append variable would be like this
为了简化事情追加变量会是这样的
protected $appends = ['id_hash','test_var'];
The method would be defined in the model like this
该方法将像这样在模型中定义
public function getTestVarAttribute(){
return "Hello world!";
}