Проблемы с laravel с мутаторами
Мое путешествие в 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));
}
}
Теперь, когда я запрашиваю базу данных со следующим И удаляет мутаторы, все работает так, как ожидалось, и я получаю ожидаемые данные:
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
порядок столбцов изменяется и включает столбец, который я изначально не запрашивал. Как правильно реализовать мутаторы и почему меняются столбцы?
Я неправильно понял это?
Спасибо
Луч
Ответы
Ответ 1
Мутаторы будут вызваны, потому что код построен таким образом. См. Реализацию этой функции в классе Eloquent Model (который вызывается toArray()
):
/**
* Convert the model 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