如何在Laravel订购关系? [英] How do I order a relationship in Laravel?
本文介绍了如何在Laravel订购关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在StackOverflow中看到了这个问题,但是我无法回答,因为它被错误地标记为重复.但是$ user-> posts与Posts :: all()不同.因此,如果您有用户"和帖子",那么如何对帖子进行排序?
I saw this question in StackOverflow, but I could not answer it because it was mistakenly marked as duplicate. However $user->posts is not the same as Posts::all(). So if you have User and Post, how do you sort the posts?
推荐答案
是的,回答我自己的问题只是为了帮助自己.请注意,将帖子作为var调用与将帖子作为方法调用不同. var解析为查询结果,该方法解析为查询生成器.
Ya, answering my own question just to help out. Note that calling posts as a var is different than calling posts as a method. The var resolves to the query result, the method resolves to the query builder.
class User extends Model implements ... {
public function posts(){
return $this->hasMany('App\Post');
}
/*
/**
* $this->posts is already a collection after query
*/
public function recentPosts($limit = 5){
return $this->posts
->sortByDesc(function ($post){
return $post->created_at;
})->take($limit);
}
/**
* $this->posts() is the query builder
*/
public function latestPosts($limit = 5){
return $this->posts()
->orderBy('created_at', 'desc')
->limit($limit)
->get();
}
}
这篇关于如何在Laravel订购关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文