Laravel中的mutators存在问题

3

我正在进行从laravel 3到laravel 4的转换...

我有一个Article模型,访问名为articles的表。

我已经设置了以下变形器来配置该模型:

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,并且为什么列会改变?

我是否理解有误?

谢谢


似乎是Eloquent\Model中的一个bug。为什么无法将collection(而不是数组)传递到视图中? - radmen
嗨。我最终将数据传递给datatables插件,并将使用一个对象。然而,相同的损坏发生了(添加valid_until属性)。现在仅出于测试目的将其传递到数组中,以便我可以查看结果。这些结果与对象中的结果相似(顺序和列顺序等)。我没有预料到列重新排序或添加列-在L3中没有发生。 - Ray
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


当我将其放入L3中时,我仅得到了包含在查询中的列/字段。因此-有了这个函数,每次我从该模型调用时,我都会获得额外的列,无论我是否需要它们?我以为它只会修改并返回查询中存在的数据? - Ray
我认为你是正确的,代码没有做它应该做的事情。我猜你应该在Github上开一个问题来讨论这个问题。 - Aloys

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接