Eloquent:嵌套查询以在有限结果中恢复顺序

时间:2015-02-23 12:02:52

标签: mysql laravel laravel-4 eloquent

以下功能(在我的用户模型中)为我的聊天系统提供了正确的结果。几乎......我需要恢复结果的顺序。

public function getChatConv($cp, $page=1){
    $limit = $page * 20;
    $user = Authek::curUser();
    $res = Chatmessage::where('receipient',$cp)->where('sender',$user->id)
                    ->orWhere('receipient',$user->id)->where('sender',$cp)
                    ->orderBy('created_at','desc')->take($limit)->get();
    return $res;
}

它返回一个对象,我需要一个对象作为结果。我已经尝试将结果转换为数组,恢复顺序,然后将数组转换回对象。这没有用。

我需要的是嵌套查询,如下面的原始SQL查询:

SELECT * 
FROM (
 SELECT * 
 FROM chatmessages
 WHERE (
  receipient =  '422'
  AND sender =  '22'
 )
 OR (
  receipient =  '22'
  AND sender =  '422'
 )
 ORDER BY created_at DESC 
 LIMIT 0 , 20
)faketable
ORDER BY created_at ASC

有一些关于嵌套查询的文章,但是我没有找到类似的案例,如果有人可以在Eloquent中执行此操作而不使用Raw查询,那将是很好的...这一定是可能的。< / p>

1 个答案:

答案 0 :(得分:0)

试试这个..

使用take()和skip(),offset()

get 4 items from offset 3/4th:
Chatmessage::take(4)->offset(3)->get();
Or this (get 10 items from 8rd row):
Chatmessage::take(10)->skip(2)->get();

public function getChatConv($cp, $page=1){
    $limit = $page * 20;
    $user = Authek::curUser();
    $res = Chatmessage::where('receipient',$cp)->where('sender',$user->id)
                    ->orWhere('receipient',$user->id)->where('sender',$cp)
                    ->orderBy('created_at','desc')->take(3)->skip(2)->get();
    return $res;
}