如何始终将属性附加到Laravel Eloquent模型?

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)

  • 不,当你添加`protected $ with = ['user']时,它会在你获得模型时自动加载.当您需要模型上数据库中不可用的数据时,附加用于. (3认同)
  • 你的用例有点奇怪,因为与`User`的关系可以让你使用'$ model-> user`而无需使用append.此外,当模型转换为JSON或转换为数组时,如果已加载该关系,则"user"键将存在.如果您总是希望用户将"protected $ with = ['user'];`添加到模型中. (2认同)

Hem*_*mar 5

我发现这个概念很有趣,我学习和分享东西。在这个例子中,我附加了 id_hash 变量,然后通过这个逻辑转换为方法,它接受第一个字符并转换为大写,即 Id 和下划线后的字母为大写,即哈希。

Laravel 本身添加了getAttribute来将它提供的所有内容组合在一起 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)