【问题标题】:orderBy on whereHas query in Laravel 4.2orderBy 在 Laravel 4.2 中查询 whereHas
【发布时间】:2015-07-29 10:23:34
【问题描述】:

如何使用 whereHas 对查询的返回数据进行排序?在我的查询中,我必须获取 id 存在于 interest 表中的用户数据,但我需要使用 interest 中的 datetime 列对其进行排序。但是,返回查询根本不对数据进行排序。

这是我的代码 sn-ps 以帮助您理解我的问题。

模型(名称:用户)

//***relationship***//
public function interest(){
     return $this->belongsTo('Interest','id','interest_by');
}

控制器

$userInterested = User::whereHas('interest',function($q) use ($id) {
     return $q->where('interest_on', $id)
              ->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;

【问题讨论】:

  • 哦,我设法为我的问题找到了解决方案,在查询生成器上使用 join() 就满足了我的需要。但是,如果您有任何其他解决方案,请随时发布。

标签: php laravel orm eloquent


【解决方案1】:

从 where has 中删除 return 并尝试 this.like

$userInterested = User::whereHas('interest',function($q) use ($id) {
  $q->where('interest_on', $id)
          ->orderBy('datetime');
 })->get();
 return $userInterested;

【讨论】:

    【解决方案2】:
    $userInterested = User::whereHas('interest',function($q) use ($id) {
         return $q->where('interest_on', $id);
    })->orderBy('datetime');
    $userQuery = $userInterested->get();
    return $userQuery;
    

    【讨论】:

    • 试过了,但它不起作用,它试图在 users 表上查找 datetime 而不是 interest跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2015-04-18
    • 1970-01-01
    相关资源
    最近更新 更多