在决定转到php框架后,我刚刚学会了laravel。我正在使用一个雄辩的查询从数据库中检索文章的结果集:
$posts = Article::select(array('articles.id','articles.article_date','articles.image_link','articles.headline','articles.category', 'articles.published'));这工作得很好,结果就像预期的那样。
但是,我现在希望将整个集合的文章日期格式从mysql日期格式更改为另一种格式。
我考虑过遍历对象并使用常用的php方法进行更改,但我想知道是否有更简单的方法来操作数据,无论是在启动查询时还是在对象本身进行批量处理时。
我看过变种人吗?但不确定这是否合适,也不确定如何实现
如有任何帮助,敬请指教
发布于 2013-05-24 16:42:02
你说得对,变种人是不错的选择。(Laravel 3语法)
Getter and Setter documentation for Eloquent models
public function get_article_date()
{
return date('d-m-Y H:i:s', strtotime($this->get_attribute('article_date'));
}获取属性
$articles = Articles::get(array(
'article_date',
'image_link',
'headline',
'published'
));
foreach($articles as $article)
{
echo $article->article_date;
}每次从模型中获取日期时,它都会首先通过赋值函数返回修改后的结果。
对于这样的事情,绝对不需要运行原始查询。
编辑被设置和混淆...需要更多咖啡(答案已编辑)
发布于 2013-05-24 16:29:43
我不确定这是否有效,但请试一试
$posts = Article::select(array('articles.id',DB::raw('CAST(articles.article_date as date)'),'articles.image_link','articles.headline','articles.category', 'articles.published'));https://stackoverflow.com/questions/16730572
复制相似问题