从 Laravel eloquent 操作结果集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16730572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
manipulate a result set from laravel eloquent
提问by Ray
I've just picked up laravel after deciding to move to a php framework. I'm retrieving a result set of articles from a database using an eloquent query:
在决定转向 php 框架后,我刚刚选择了 laravel。我正在使用雄辩的查询从数据库中检索文章的结果集:
$posts = Article::select(array('articles.id','articles.article_date','articles.image_link','articles.headline','articles.category', 'articles.published'));
this works fine and results come out as expected.
这工作正常,结果如预期。
However I now want to change the format of the article date from the mysql date format to another for the entire collection.
但是,我现在想将文章日期的格式从 mysql 日期格式更改为整个集合的另一种格式。
I thought about iterating through the object and changing using the usual php methods but wondered if there was an easier way to manipulate the data either when initiating the query or en mass with the object itself.
我考虑过遍历对象并使用通常的 php 方法进行更改,但想知道是否有更简单的方法来操作数据,无论是在启动查询时还是在对象本身的整体上。
I've looked at mutators? but wasnt sure if this was appropriate or how to implement
我看过突变体?但不确定这是否合适或如何实施
Any help, pointers appreciated
任何帮助,指针表示赞赏
回答by David Barker
You're right, mutators are the way to go. (Laravel 3 syntax)
你是对的,突变器是要走的路。(Laravel 3 语法)
Getter and Setter documentation for Eloquent models
Eloquent 模型的 Getter 和 Setter 文档
public function get_article_date()
{
return date('d-m-Y H:i:s', strtotime($this->get_attribute('article_date'));
}
Getting the attribute
获取属性
$articles = Articles::get(array(
'article_date',
'image_link',
'headline',
'published'
));
foreach($articles as $article)
{
echo $article->article_date;
}
Every time you get the date from your model it will run through the mutator first returning your modified result.
每次从模型中获取日期时,它都会通过 mutator 首先返回修改后的结果。
Absolutely no need to run raw queries for something like this.
绝对不需要为这样的事情运行原始查询。
EDITgot set and get mixed up... more coffee needed (answer edited)
编辑已设置并混淆......需要更多咖啡(答案已编辑)
回答by Kristijan
Im not sure if this is working, but give it a try
我不确定这是否有效,但试一试
$posts = Article::select(array('articles.id',DB::raw('CAST(articles.article_date as date)'),'articles.image_link','articles.headline','articles.category', 'articles.published'));