Correspondence between two users in the correct order

I want to create a chat system on which I could list all the chats between two specific people

I have 2 tables usersandchats

There are 3 columns - user_id, friend_idandchat

My model file is User.phpas follows

public function chats() {
    return $this->hasMany('App\Chat');
}

For instance,

I want to list the entire chat between user 1 and 3 without changing the order of the conversation.
I can just do this by completing $chats = Auth::user()->chats->where('friend_id', '=', $id);, but this will only give authenticated users (who are users 1 or 3). But I want to talk between them.
So I found an alternative way to do this with

$first = Chat::all()->where('user_id', '=', Auth::user()->id)->where('friend_id', '=', $id);
$second = Chat::all()->where('user_id', '=', $id)->where('friend_id', '=', Auth::user()->id);
$chats = $first->merge($second);

. . , .

, , ?
, .

+4
4

, .

Chat::where(function ($query) use ($id) {
    $query->where('user_id', '=', Auth::user()->id)
          ->where('friend_id', '=', $id);
})->orWhere(function ($query) use ($id) {
    $query->where('user_id', '=', $id)
          ->where('friend_id', '=', Auth::user()->id);
})->get();

, , - , . , ( , ), .

+2

, all(). , , PHP.

:

:

Schema::create("chat", function (Blueprint $table) {
    //Other creation lines
    $table->timestamps();
})

:

public function scopeInvolvingUsers($query, $userId,$friendId) {
     return $query->where([ ["user_id",$userId],["friend_id",$friendId] ])
                  ->orWhere([ ["user_id",$friendId],["friend_id",$userId] ]);
} 

:

$chats = Chat::involvingUsers(\Auth::id(),$otherId)->latest()->get();

, latest earliest , timestamps .

+2

$first = Chat::all()->where('user_id', '=', Auth::user()->id)
         ->where('friend_id', '=', $id)->get();
$second = Chat::all()->where('user_id', '=', $id)
          ->where('friend_id', '=', Auth::user()
          ->id)->get();
$chats = $first->merge($second)
         ->sortBy('created_at');//created_at is timing added change if other
+1

, . ,

$table->timestamps();

and you can select the chat associated with the user and sort it by created_at. In laravel 5.3+ use

Chats::where(['user_id', '=', Auth::id()], ['friend_id', '=', $id])->orWhere(['user_id', '=', $id], ['friend_id', '=', Auth::id()])->sortBy('created_at');
+1
source

Source: https://habr.com/ru/post/1688021/


All Articles