变异器的laravel问题

时间:2013-06-07 13:44:03

标签: php laravel eloquent mutators

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

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

我已经使用以下变更器设置了模型:

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

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

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以及为什么列会发生变化?

我误解了吗?

由于

1 个答案:

答案 0 :(得分:0)

将调用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