php - laravel 与突变体的问题

标签 php laravel eloquent mutators

我(从 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));
}

}

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

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

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

我是不是理解错了?

谢谢

最佳答案

修改器将被调用,因为代码是以这种方式构建的。参见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

关于php - laravel 与突变体的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985656/

相关文章:

php - 与依赖注入(inject)的绑定(bind)不起作用。目标不可实例化

laravel - 如何使用 Mongodb 查询数组键值 Laravel 中的位置

php - 如何将 Eloquent 中的连接设置为每个查询的默认值?

database - Vue.js 和 Laravel 一次调用更新多行

php - PHP 版本字符串中的 lenny8 是什么?

php - 根据最新的关联对象查询

php - 中间表和 Laravel

Laravel - 创建和附加 - 多对多关系

php - mysql通配符IN数据库

php - 如何更改默认的 Netbeans 7 项目目录?