php - Get room for each user in chat room application considering users access level

564

I have two tables: room and with_access_room

id | name | access_level | image_id     --- room

user_id | room_id | token               --- with_access_room

There are 3 type of rooms:

  • Public: everyone can see it (doesn't matter registered or not)
  • Private: only registered users see it
  • Private with access: only registered user can create and nobody can see it except creator which gets special token to invite other users.

Now in main page I have to show my rooms. Consider I have a user with id = 1. So he can see all public, private (without access token needed) and private rooms (with access) created by him.

In access_level column 0 is public and 1 is private.

For example:

room

id   |   name  |  access_level  |  image_id
1    |   aaa   |      1         |     1
2    |   bbb   |      0         |     2
3    |   ccc   |      1         |     3
4    |   ddd   |      1         |     4

with_access_room

user_id | room_id | token
   1    |    3    |  xyz
   2    |    4    |  zyx

So my user with id = 1 must see these "table"

ID | name | access_level | image_id | token
1  | aaa  |     1        |    1     | NULL
2  | bbb  |     0        |    2     | NULL
3  | ccc  |     1        |    3     | xyz

I am working with Yii 2

Which SQL query or Yii 2 model method with params can give me desired result ?

601

Answer

Solution:

I don't think you have described enough information to represent the problem. Missing information:

  • How is "Private with access" represented in the data?
  • Where is the "creator" represented?
  • How do we know who is registered?

I can guess reasonable answers to these questions. In the end, the query will look something like this:

select r.*
from room r
where access_level = 0 or
      (access_level = 1 and
       1 in (select user_id from users u where is_registered = 1)
      ) or
      (access_level = 2 and
       1 in (select user_id from with_access_room war where war.room_id = r.id)
      );

This assumes that the creator has a row inwith_access_room.

51

Answer

Solution:

This query should work:

select `id`, `name`, `access_level`, `image_id`, `token` from `room`
   left join `with_access_room` on `id`=`room_id`
   where `access_level`=0
   or `user_id`=1
   or `id` not in (select `room_id` from `with_access_room`)
   order by `id`

People are also looking for solutions to the problem: php - Proceed to credit card payment method in PayPal

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.