Reducing database query sizes in laravel - php

I'm looking to reduce the my query size in laravel.
My query looks something like this (I shortened it, it's about 10 times this amount of lines):
$users = User::where("interface_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("interface_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("web_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("web_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("illustration_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("illustration_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("brush_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("brush_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("typography_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("typography_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("identity_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("identity_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orWhere("vector_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', $unavailableCheck)
->orWhere("vector_art", '=', 1)->where('role', '=', 2)->where('commstatus', '=', 1)
->orderBy($orderByString, 'desc')
->paginate(1);
As you can see, it's a bit redundant.
For every art type, I'm looking to get users by the role of "2", if their commstatus is equal to "1" or "$unavailable".
At first, I tried to shorten it by not adding "role" or "commstatus" at the end of each "where" clause, and at the bottom writing another $users = $users::where("role", "=", "2"), for example, but I can't seem to be able to find the right syntax that.
Is there any way to shorten this query?

You certainly shouldn't need to duplicate where('role', '=', 2)->where('commstatus', '=', $unavailableCheck) for every single type of art, as they're effectively ANDed conditions; and consider whereIn('commstatus', [$unavailableCheck, 1]) rather than having two equality checks.
Something like:
$users = User::where('role', '=', 2)
->whereIn('commstatus', [$unavailableCheck, 1])
->where("interface_art", '=', 1)
->orWhere("web_art", '=', 1)
->orWhere("illustration_art", '=', 1)
->orWhere("brush_art", '=', 1)
->orWhere("typography_art", '=', 1)
->orWhere("identity_art", '=', 1)
->orWhere("vector_art", '=', 1)
->orderBy($orderByString, 'desc')
->paginate(1);

As others have stated, your schema would likely benefit from refactoring towards normalization. However, I believe you can still refactor your existing query to be less redundant and more readable.
Laravel has the ability to handle Advanced Where Clauses which include nested parameter groupings. From the documentation:
The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.
With that in mind, you should be able to refactor the query like this:
$users = User::whereIn('commstatus', [$unavailableCheck, 1])
->where('role', 2)
->where(function ($query) {
$query->where("interface_art", 1)
->orWhere("web_art", 1)
->orWhere("illustration_art", 1)
->orWhere("brush_art", 1)
->orWhere("typography_art", 1)
->orWhere("identity_art", 1)
->orWhere("vector_art", 1);
})
->orderBy($orderByString, 'desc')
->paginate(1);
That will create a SQL query that does:
SELECT * FROM users
WHERE commstatus IN ($unavailableCheck, 1)
AND role = 2
AND (interface_art = 1 OR illustration_art = 1 OR ... etc)

Related

Laravel select all rows if id exists in another table and a column has specific values on that table

I have 4 tables:
notices (id, title, desc, is_published)
notices_to_districts (id, notice_id, district_id)
notices_to_employees (id, notice_id, user_id)
notices_to_establishments (id, notice_id, establishment_id)
I want to get all unique notices if,
notices_to_districts has a specific district_id, or
notices_to_employees has a specific user_id, or
notices_to_establishments has a specific establishment_id
I am trying -
$notices = Notice::join('notices_to_districts', 'notices_to_districts.notice_id', '=', 'notices.id')
->join('notices_to_establishments', 'notices_to_establishments.notice_id', '=', 'notices.id')
->join('notices_to_employees', 'notices_to_employees.notice_id', '=', 'notices.id')
->where('district_id', '=', $user_district_id)
->orWhere('establishment_id', '=', $user_establishment_id)
->orWhere('user_id', '=', $user_id)
->where('is_published', '=', 1)->get();
You should use Closure Parameter Grouping or else, your "orWhere" will not work as you wish.
$notices = Notice::join('notices_to_districts', 'notices_to_districts.notice_id', '=', 'notices.id')
->join('notices_to_establishments', 'notices_to_establishments.notice_id', '=', 'notices.id')
->join('notices_to_employees', 'notices_to_employees.notice_id', '=', 'notices.id')
->where('district_id', '=', $user_district_id)
->where('is_published', '=', 1)
->where(
function ($query) use ($user_establishment_id, $user_id) {
$query->orWhere('establishment_id', '=', $user_establishment_id)
->orWhere('user_id', '=', $user_id);
}
)
->get();
Like this example, the SQL will have the correct parentesis around your clause.
I solved it -
$notice_ids_of_district = Notices_to_district::select('notice_id')->where('district_id', '=', $user_district_id)->get();
$notice_ids_of_establishment = Notices_to_establishment::select('notice_id')->where('establishment_id', '=', $user_establishment_id)->get();
$notice_ids_of_employee = Notices_to_employee::select('notice_id')->where('user_id', '=', $user_id)->get();
$notices = Notice::whereIn('id', $notice_ids_of_district)
->orWhereIn('id', $notice_ids_of_establishment)
->orWhereIn('id', $notice_ids_of_employee)
->get();

Laravel: Query with where clause gone wrong

What I am trying to achieve is to allow teachers to import a student into different classes.
Note: A student can be multiple classes.
The problem is that when I show the list of students in a select dropdown it should return all students except for students that are not in this class (the class being the page that I am on, app.com/classes/5 for example).
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'asc')
->get();
This works and shows all students that are not in this specific class BUT if a student that's in this class and another class their name appears in the list and as duplicate names.
What can I do?
When MySQL's only_full_group_by mode is turned on, it means that strict ANSI SQL rules will apply when using GROUP BY
You should try to select fields from schema on which you can apply group by instead of select *.
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->select('users.id', 'other fields you used')
->orderBy('users.name', 'ASC')
->groupBy('users.id')
->get();
Not IN is also useful in your case
User::select('fields you used')
->role('student')
->whereNotIn('id', DB::table('group_user')->where('group_id', $id)->pluck('user_id')) // $id = 5
->orderBy('name', 'ASC')
->get();
Modify your query to use distinct() like so;
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'ASC')
->distinct()
->get();
You could also groupBy('users.id')
$students = User::join('group_user', 'users.id', '=', 'group_user.user_id')
->role('student')
->where('group_user.group_id', '!=', $id)
->orderBy('users.name', 'ASC')
->groupBy('users.id')
->get();

syntax to join a table twice in laravel

I'm trying to join the below 3 tables. The issue is in the part where I want to join posts.id to the shares.post_id using 'AND' operator which is not correct. What is the correct syntax to do that ?
$sharedPosts = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('posts', 'posts.user_id', '=', 'users.id' , 'AND' , 'posts.id', '=', 'shares.post_id')
->where('shares.user_id', '=', $myFriends)
->get();
Try aliasing:
$sharedPosts = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('posts as p1', 'p1.user_id', '=', 'users.id' , 'AND' , 'p1.id', '=', 'shares.post_id')
->join('posts as p2', 'p2.id', '=', 'shares.post_id')
->where('shares.user_id', '=', $myFriends)
->get();
You cannot join a table twice with no alias.
Although if you have 2 clauses in your join, I think you ought to do as in the documentation :
$sharedPosts = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('posts as p1', , function($join){
$join->on('p1.user_id', '=', 'users.id')
->on('p1.id', '=', 'shares.post_id')
})
->join('posts as p2', 'p2.id', '=', 'shares.post_id')
->where('shares.user_id', '=', $myFriends)
->get();
Edit (with one posts join):
$sharedPosts = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('posts', , function($join){
$join->on('posts.user_id', '=', 'users.id')
->on('posts.id', '=', 'shares.post_id')
})
->where('shares.user_id', '=', $myFriends)
->get();

Laravel/Eloquent query going wrong

I have two tables, one with users, one with the name of their document. The first table consists of two columns: id and username. The second one consists of three columns: id, userid and document_name.
Now, I'm trying to create a query in the controller. What should happen, ideally, is that if someone visits website.com/{documentname}, it displays the username of the owner. Also, this should only happen if the current logged in user is the owner of the document. However, this is proving more difficult than I imagined. As in, I can't see what I'm doing wrong.
Here's the query:
$user = DB::table('documents')
->join('users', function($join)
{
$join->on('users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
})
->get();
**Try this query :**
$user = DB::table('documents')
->leftJoin('users', 'users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
->get();
$document_name isn't in scope for the join function: you need to pass it through to the closure via use
$user = DB::table('documents')
->join('users', function($join) use ($document_name)
{
$join->on('users.id', '=', 'documents.userid')
->where('documents.userid', '=', Auth::id())
->where('documents.document_name', '=', $document_name);
})
->get();
EDIT
Because the WHERE conditions apply to the base table, and not to the JOIN:
$user = DB::table('documents')
->join('users', function($join) {
$join->on('users.id', '=', 'documents.userid')
})
->where('userid', '=', Auth::id())
->where('document_name', '=', $document_name);
->get();

Perform JOIN on three or four different tables in Laravel syntax

TABLES X(ID,A_ID)A(ID,B_ID),B(ID,C_ID),C(ID,D_ID)D(id,VALUE)
I want to retrieve the value of D table using laravel syntax on basis of X table Id and perform a JOIN with other tables.
Please post answers only in laravel syntax. In other format I can do. I am new to it so.
X::select('value')
->join('a', 'X.a_id', '=', 'a.id')
->join('b', 'a.b_id', '=', 'b.id')
->join('c', 'b.c_id', '=', 'c.id')
->join('d', 'c.d_id', '=', 'd.id')
->where('x.id', '=', $val)
->get();
But it is not working. please provide me proper solution. Right now I am using PHP logic to get the value, rather than optimise the query.
There are many ways, but this is the basic:
$rows = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('follows', 'follows.user_id', '=', 'users.id')
->where('follows.follower_id', '=', 3)
->get();
doc
Try this:
DB::table('X')
->join('a', 'X.a_id', '=', 'a.id')
->join('b', 'a.b_id', '=', 'b.id')
->join('c', 'b.c_id', '=', 'c.id')
->join('d', 'c.d_id', '=', 'd.id')
->select('D.value')
->where('x.id', '=', $val)
->get();
$result = X::select('a.value', 'd.*')
->join('a', 'x.a_id', '=', 'a.id')
->join('b', 'a.b_id', '=', 'b.id')
->join('c', 'b.c_id', '=', 'c.id')
->join('d', 'c.d_id', '=', 'd.id')
->where('x.id', '=', $val)
->get();
foreach ($result as $row) {
# code...
}

Categories