A
A
Analka2020-01-19 17:09:05
MySQL
Analka, 2020-01-19 17:09:05

When in laravel mysql query?

how to write query in laravel
need to output all my dialogs if user_id = 1 or recipient_id= 1
dialogs table
id | user_id | recipient_id| status | ip
started like this but don't know how to check my id if i can be user_id sender or recipient recipient_id

если dialogs.users_id = 1 (моему id), то users.id=dialogs.recipient_id
    если dialogs.recipient_id= 1(моему id), то users.id = dialogs.user_id

I read about when, but I can’t figure out how to substitute a check with the users table
$dialogs = DB::table('dialogs')
                ->leftJoin('users',
                    when('dialogs.user_id','=', Auth::user()->id,function ($query){
                        return $query->where('users.id','=', 'dialogs.recipient_id');
                    })
                    ->when('dialogs.recipient_id','=', Auth::user()->id,function ($query){
                        return $query->where('users.id','=', 'dialogs.user_id');
                    })
                )
                ->leftJoin('user_attributes','user_attributes.user_id','=','users.id')->get();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-02-09
@dlnsk

It seems to me that your base is not properly designed. Where is your message text? In a separate table? In this case, it turns out that the dialogue initiated by A to B and vice versa B to A are different dialogues, which is not the case in real life (messengers).
Your table should look like
id | user_id | recipient_id | message | timestamp
This will allow you to easily select all the messages in one conversation, sort them by time, and display them. The chat list is also easy to display - it's a many-to-many relationship between users and users (yes, yes!), where dialogs is a pivot table.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question