1

I am trying to write a MySQL select query using Laravel's Database Query Builder as follows:

Select all projects where the project's author_id equals the user's id , or where the project's group_id equals a group_id that the user is assigned to.

For example:

User 1 is in group 24. There are 3 projects in group 7. User 1 wants to see all of the projects from that group.

Database Tables:

users

+----+
| id |
+----+

projects

+-----------+----------+
| author_id | group_id |
+-----------+----------+

groups

+----+
| id |
+----+

groups_users_are_assigned

+---------+----------+
| user_id | group_id |
+---------+----------+

Any help on how to do this correctly in a single query would be amazing. Thanks!

1
  • Lavarel or Laravel ? Commented Apr 20, 2014 at 20:26

1 Answer 1

1

A don't want to create a test enviroment for this query, but according to my knowledge, this should work:

DB::table('projects')
    ->leftJoin('groups_users_are_assigned', 'projects.group_id', '=', 'groups_users_are_assigned.group_id')
    ->where('author_id', '=', $userId)
    ->orWhere('groups_users_are_assigned.user_id', '=', $userId)
    ->get()
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent - thank you, works perfectly. The 'orWhere' needed the equals operator passed as the second argument, and $userId as third.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.