在我的用户模型中,我添加了自定义属性获取的帖子用户数量。 我可以成功地做到这一点,但是当我尝试按顺序排序时会给出错误。
1054 Unknown column 'posts' in 'order clause'
答案 0 :(得分:0)
您能告诉我们您正在运行的Eloquent查询是什么吗?另外,请确保您使用的表格名称正确无误。
编辑:
posts表列中是否存在posts列?或者您是否尝试从帖子模型中获取所有帖子并按名称按降序排列帖子?
如果您想要这样做,那么您需要转到您的用户模型并设置与帖子的关系。
在用户模型中创建此方法:
public function posts() {
return $this->hasMany('Post'); // Post would be the name of the Posts Model
}
在Post模型中执行此操作:
public function user() {
return $this->belongsTo('User'); // Where User is the name of the Users Model
}
然后根据Laravel文档,您可以使用查询执行类似的操作:
$users = User::with(array('posts' => function($query)
{
$query->orderBy('name', 'desc'); // assuming that 'name' would be the column in the posts table you want to sort by
}))->take(5)->get();
我希望我是正确的,这有助于解决你的问题。