Laravel-如何按ID

时间:2019-08-09 18:05:09

标签: php mysql arrays laravel sorting

我需要按照ID称为$ messages的ID升序对对象数组进行排序,我尝试了很多操作,但似乎没有任何作用。这是我尝试过的:

public function getMessagesPage(Request $request)
    {
        $user_id = $request->session()->get('id');

        $user_second = User::where('username', $request->username)->first();

        $messages_1 = Messages::where('user_1', $user_id, 'AND')->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
        $messages_2 = Messages::where('user_2', $user_id, 'AND')->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();

        $messages = $messages_1->merge($messages_2);

        $messages = collect($messages);
        $messages->sortBy('id');

        return view('messages')->with('messages', $messages)->with('user_id', $user_id)->with('user_second', $user_second);
    }

2 个答案:

答案 0 :(得分:1)

您可以使用sortBy()对集合进行排序,但是请记住,该函数会返回对集合进行排序的,不会对原始集合进行更改,因此您必须更改此行:

//$messages->sortBy('id');
$messages = $messages->sortBy('id');

作为更好的选择,您可以仅通过一个查询来获得所有已排序的邮件

$messages = Messages::where([['user_1', $user_id], ['user_2', $user_second->id]])
               ->orWhere([['user_2', $user_id], ['user_1', $user_second->id]])
               ->orderBy('id', 'asc')
               ->get()

这与编写此SQL相同:

select * from messages 
    where (user_1 = $user_id and user_2 = $user_second->id) 
    or (user_2 = $user_id and user_1 = $user_second->id) 
    order by id asc

答案 1 :(得分:0)

您可以尝试

$messages_1 = Messages::where('user_1', $user_id)->where('user_2', $user_second->id)->orderBy('id', 'asc')->get();
$messages_2 = Messages::where('user_2', $user_id)->where('user_1', $user_second->id)->orderBy('id', 'asc')->get();

从第一个WHERE中删除AND。 Eloquent知道,如果您链​​接->where()子句,则在它们之间使用AND。

或者,如果您使用的是 Laravel 5.3或更高版本,则可以将数组传递给where子句

$messages_1 = Messages::where([
     'user_1' => $user_id,
     'user_2' => $user_second->id])
->orderBy('id', 'asc')
->get();

或者,如果以下$messages = collect($messages);正确返回了键/值对数组,则您应该可以简单地使用以下

return view('messages')
    ->with([
       'messages'    => sort($messages),
       'user_id'     => $user_id,
       'user_second' => $user_second
    ]);