Mus*_*kat 10 php api restful-architecture laravel laravel-5
我想知道如何总是将一些数据附加到Eloquent模型而不需要它,例如在获取Posts表单数据库时我想将每个用户的用户信息附加为:
{
id: 1
title: "My Post Title"
body: "Some text"
created_at: "2-28-2016"
user:{
id: 1,
name: "john smith",
email: "example@mail.com"
}
}
Run Code Online (Sandbox Code Playgroud)
Mus*_*kat 18
经过一些搜索,我发现你只需要$appends在你的Eloquent模型中将你想要的属性添加到数组中:
protected $appends = ['user'];
Run Code Online (Sandbox Code Playgroud)
更新:如果数据库中存在该属性,您可以
protected $with= ['user'];根据David Barker的评论使用
然后创建一个Accessor:
public function getUserAttribute()
{
return $this->user();
}
Run Code Online (Sandbox Code Playgroud)
这样,您始终可以将每个帖子的用户对象视为:
{
id: 1
title: "My Post Title"
body: "Some text"
created_at: "2-28-2016"
user:{
id: 1,
name: "john smith",
email: "example@mail.com"
}
}
Run Code Online (Sandbox Code Playgroud)
我发现这个概念很有趣,我学习和分享东西。在这个例子中,我附加了 id_hash 变量,然后通过这个逻辑转换为方法,它接受第一个字符并转换为大写,即 Id 和下划线后的字母为大写,即哈希。
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);
}
}
Run Code Online (Sandbox Code Playgroud)
为了简化事情追加变量会是这样的
protected $appends = ['id_hash','test_var'];
Run Code Online (Sandbox Code Playgroud)
该方法将像这样在模型中定义
public function getTestVarAttribute(){
return "Hello world!";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19544 次 |
| 最近记录: |