【问题标题】:Laravel orm Order by custom attributeLaravel orm 按自定义属性排序
【发布时间】:2015-02-09 19:53:40
【问题描述】:

在我的用户模型中,我添加了自定义属性获取用户创建的帖子数量。 我可以成功地得到它,但是当我尝试按它订购时会出错。

1054 Unknown column 'posts' in 'order clause' 

【问题讨论】:

    标签: laravel-4 orm


    【解决方案1】:

    您能否告诉我们您正在运行的 Eloquent 查询是什么?还要确保您使用的表的名称是正确的。

    编辑:

    用户表中是否存在帖子列?或者您是否尝试从 Post 模型中获取所有帖子并按帖子名称按降序排列?

    如果这是您想要做的,那么您需要转到您的用户模型并设置您与帖子的关系。

    在用户模型中创建这个方法:

    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();
    

    我希望我是正确的,这有助于解决您的问题。

    【讨论】:

    • User::select(array('id', 'username'))->orderBy('posts', 'desc')->take(5)->get();跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多