繁体   English   中英

变异器的laravel问题

[英]laravel problems with mutators

我进入laravel 4(来自laravel 3)的旅程仍在继续......

我有一个文章模型,访问一个名为文章的表。

我用以下的mutator设置了模型:

class Article extends Eloquent {

 public function getArticleDateAttribute($value)
{
    return date('d/m/Y', strtotime($value));
}

public function getValidUntilAttribute($value)
{
    return date('d/m/Y', strtotime($value));
}

}

现在,当我使用以下内容查询数据库时,删除mutators一切都按预期工作,我得到了我期望的数据:

public function getTest() {

    $data = Article::select(array(
        'articles.id',
        'articles.article_date',
        'articles.image_link',
        'articles.headline',
        'articles.category'
    ))  ->get()
        ->toArray();
    var_dump($data);
    //return View::make('_layouts.master');
}

在我的测试中,我得到的结果与此样本一样:

array (size=5)
  'id' => int 3
  'article_date' => string '2008-06-03 00:00:00' (length=19)
  'image_link' => string '' (length=0)
  'headline' => string 'Sussex Amateur Course Closure' (length=29)
  'category' => int 6

现在,当我添加回变量器时,使用确切的查询我得到以下数据:

array (size=6)
  'article_date' => string '03/06/2008' (length=10)
  'valid_until' => string '01/01/1970' (length=10)
  'id' => int 3
  'image_link' => string '' (length=0)
  'headline' => string 'Sussex Amateur Course Closure' (length=29)
  'category' => int 6

列顺序已更改,并且包含了我最初未请求的列。 我应该如何正确实现mutators以及为什么列会发生变化?

我误解了吗?

谢谢

射线

将调用mutator,因为代码是以这种方式构建的。 请参阅Eloquent Model类中的此函数的实现(由toArray()调用):

/**
 * Convert the model's attributes to an array.
 *
 * @return array
 */
public function attributesToArray()
{
    $attributes = $this->getAccessibleAttributes();

    // We want to spin through all the mutated attributes for this model and call
    // the mutator for the attribute. We cache off every mutated attributes so
    // we don't have to constantly check on attributes that actually change.
    foreach ($this->getMutatedAttributes() as $key)
    {
        if ( ! array_key_exists($key, $attributes)) continue;

        $attributes[$key] = $this->mutateAttribute($key, $attributes[$key]);
    }

    return $attributes;
}

https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Model.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM