【问题标题】:Laravel 4 Present ModelLaravel 4 当前模型
【发布时间】:2014-10-30 17:34:23
【问题描述】:

在 Laravel 4 中,我有一个链接到数据库表的模型。我们就叫它Model吧。

假设此模型有一个名为Property AProperty B 的数据库列。

当我对我的模型(即Model::all()Model::find($id)前端作为某种只读字段,即Property C

我需要在这里使用演示者库,还是有办法在 Laravel 4 中覆盖模型函数?

对我来说,关键是当我调用Model::all()时,该属性会出现

编辑:

据我了解,这应该返回一个名称为 foo 的属性,其值始终为 "foo"

型号

class DiscountLink extends Eloquent {
    protected $table = 'discountLinks';
    protected $hidden = array('tag');
    protected $fillable = array('name', 'currency', 'language', 'price', 'instalments', 'expires', 'active', 'foo');

    public function getFooAttribute()
    {
        return "foo";
    }
}

控制器

class DiscountLinkController extends \BaseController {
    public function index()
    {
        return DiscountLink::all();
    }
}

【问题讨论】:

    标签: php rest laravel


    【解决方案1】:

    在您的Model 中使用accessor。连接 A 和 B,例如:

    public function getPropertyCAttribute()
    {
        return $this->attributes['property_a'] . ' ' . $this->attributes['property_b'];
    }
    

    然后您可以访问Model::find($id)->propertyC

    如果您希望属性自动包含在模型的结果数组中(例如,如果您将 Model::all()Model::get() 的结果作为 JSON 发送),请在顶部添加 $appends 声明您的模型:

    protected $appends = array('PropertyC');
    

    如果函数是可以在数据库中完成的(例如连接、求和等),您还可以在查询中添加DB::raw 命令,例如:

    Model::select(*, DB::raw('CONCAT(PropertyA, " ", PropertyA) AS PropertyC'))->...
    

    【讨论】:

    • 我打电话给Model::all()时应该出现propertyC吗?
    • 是的,一旦您遍历结果以访问各个行。因此,如果您调用了$model=Model::all(),那么您可以访问foreach ($model ad $m) { var_dump($m->propertyC) }; 内的propertyC。另外,确保$this->attributes[''] 中的值是数据库中的实际字段名称;它区分大小写,因此如果您的列名为property_a,访问者应引用$this->attributes['property_a'];
    • 假设我有这个函数:public function getFooAttribute() { return "goooglelelgoo"; } 那么我应该总是返回一个名为 Foo 的属性吗?
    • 是的,对于结果集中的每个 $element,位于 $element->foo
    • 目前对我来说还没有发生,我已经用我的完整模型更新了我的问题。
    猜你喜欢
    • 2016-07-23
    • 2018-06-10
    • 2020-09-08
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    相关资源
    最近更新 更多