将列添加到 Eloquent

Add column to Eloquent

我正在尝试使用下一行获取 Eloquent 集合:

Document::with('more_information')->anyScope()->get()

我得到一个包含 20 个“”的集合,但我想添加另一个列来格式化日期,以便轻松地与其他组件交互而不是格式化每个组件中的日期。

要添加此列,我可以重写 21 个列名称并编写更多行以获得使用我的 with...调用的集合,但这看起来不太好。 ..

有没有办法简单地添加我的第 21 列而不重写其他 20 列?

我阅读了一些有关 addSelect 的内容,但在我的代码中它忽略了我的前 20 列

终于搞定了,做下一个就可以了:

Document::with('more_information')->anyScope()->get('*',<aditional columns>)

更新: 寻找另一种更合适的方法来完成我的任务,我发现 accessors 和模型 属性 $appends

使用下一个脚本,我可以使用自定义列检索我的 collection。值得一提的是,如果您不使用 $appends,访问器可以正常工作,但它不会在数组中返回。不建议多次使用 $appends 因为它会对性能产生负面影响

class Trabajador extends Model {

    protected $appends = ["fullName"];

    public function getFullNameAttribute() {
         return $this->attributes['nombre'] . $this->attributes['apellidos'];
    }
}