我(从 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/