Laravel Eloquent:如何在Json响应中生成假列?

Pag*_*aou 3 php laravel eloquent laravel-5 laravel-5.1

我有两个模型:UaiInformation一个hasOne关系.

Uai (uai_id, a)
Information (uai_id, b)
Run Code Online (Sandbox Code Playgroud)

我想生成一个包含以下内容的Json响应:

  • 所有Uai记录
  • 一个"假"列truewhitch 说如果hasOne Relationship存在于Uai和之间,Information并且false如果没有关系

任何的想法 ?

在此先感谢Paguemaou

编辑一个 感谢jedrzej.kurylo的回答.我如何使用uai_id当前行中的fake column getter?我使用getter和seeter但我从不尝试使用另一列的内容.能给我举个例子 ?

如果我理解,我可以使用fake column name在其他列名称中选择.我是真的吗?

jed*_*ylo 6

Eloquent允许您轻松地将自定义字段添加到模型的JSON表示中.

首先,您需要通过在模型类中定义$ appends属性来定义其他字段的列表:

protected $appends = ['fakeColumnName'];
Run Code Online (Sandbox Code Playgroud)

其次,为假列添加一个getter,它将为自定义列提供值:

public function getFakeColumnNameAttribute() {
    //here add the code that will return custom column's value
}
Run Code Online (Sandbox Code Playgroud)