3

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

我有一个 Article 模型,可以访问一个名为 article 的表。

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

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

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

我误解了这个吗?

谢谢

射线

4

1 回答 1

0

mutators 将被调用,因为代码是这样构建的。请参阅 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

于 2013-06-07T16:50:55.753 回答