ds3422222 2018-06-20 02:48
浏览 11
已采纳

显示除分配的用户以外的所有用户。 Laravel 5.6

I have a screen where admin adds topics, db name is chat_topics (id, title, status) then in edit topic screen, there are two lists with available users and assigned users.

When admins assigns users it saves in a pivot table, chat_topic_user (chat_topic_id, users_id)

Now, one user can be assign to many topics. I am able to assign users to topics, then in edit screen I am able to display all the assigned users for that specific topic.

Problem comes when I assign a specific user it even shows in available users which should not display, for example if userA is assigned to TopicA then for TopicA edit screen it shouldn't display userA in available users, right.
But userA should be displayed on TopicB edit edit screen.

I hope I am clear enough to explain the problem.

Code to display all available users:

 User::with('chat_topics')->get() 

(if userA is assigned to TopicA, so userA shouldn't be displayed in available users, but it should be displayed for TopicB available list)

Code to display only assigned users on specific topic

User::has('chat_topics')->whereHas('chat_topics', function ($query) use ($topic_id) { $query->where('id', $topic_id); })->get();

I want something like this:

TOPIC A EDIT SCREEN
- Assigned Users
user a
user b
Available Users
empty (if only two users in db)

TOPIC B EDIT SCREEN
- Assigned Users
empty
Available Users
user a
user b

Currently it displays like this:

TOPIC A EDIT SCREEN
- Assigned Users
user a
user b
- Available Users
user a
user b

Its duplicating, as one cant be assigned more than once for same topic.

Thanks in advance. would really appreciate if someone could help.

  • 写回答

1条回答 默认 最新

  • dongtai6741 2018-06-20 03:13
    关注

    Based on your code:

    $assignedUsers = User::has('chat_topics')->whereHas('chat_topics', function ($query) use ($topic_id) { $query->where('id', $topic_id); })->get();
    
    // get the list of assigned userIds
    $assignedIds = $assignedUsers->pluck('id');
    
    // get the list of available user excerpt users in $assignedUsers
    $availableUsers =  User::with('chat_topics')->whereNotIn('id', $assignedIds)->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端