I have a database query that needs filtering further. The id needs to match a number in an array I have. For some reason, I can select where using every column except id. Even something as simple as $query->where('users.id', 1); doesn't work. How can I perform a database query by id?
$portfolio_query_array = UserPortfolio::all()->pluck('user_id')
$query = DB::table('users');
$query->select('users.id as user_id','users.user_slug', 'users.social_id', 'users.social_img_update_status', 'users.avatar', 'users.first_name', 'users.last_name', 'users.bio', 'comments.rating', 'user_portfolios.title', 'user_portfolios.description', 'user_portfolios.filepath');
$query->leftjoin('comments', 'comments.comment_to', '=', 'users.id');
$query->leftjoin('user_portfolios', 'user_portfolios.user_id', '=', 'users.id');
$query->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', '=', 'users.id');
$query->where('users.status', 1);
$query->where('users.user_type', 3);
// The below simple query line doesn't work
$query->where('users.id', 1);
// The lines I do want to work also fail.
foreach ($portfolio_query_array as $user_id){
$query = $query + $query->where('users.id', $user_id);
}
Thank you for your help!
First of all, you should take advantage of Eloquent ORM, there is no need to use raw queries unless you have some performance issues or really complex queries.
Assuming you have 3 models User, UserPortfolio, Comment, and all relationships defined, you could do something as simple as this:
$users = User::with('comments', 'portfolio')
->where('status', 1)
->where('user_type', 3)
->whereHas('portfolio')
->get();
In this way, you are getting all users with portfolios which is what I assume you want.
Anyway, if you insist to use a raw query, there whereIn() method is what you need
$portfolio_query_array = UserPortfolio::pluck('user_id')->toArray();
$query = DB::table('users')
->select(
'users.id as user_id',
'users.user_slug',
'users.social_id',
'users.social_img_update_status',
'users.avatar',
'users.first_name',
'users.last_name',
'users.bio',
'comments.rating',
'user_portfolios.title',
'user_portfolios.description',
'user_portfolios.filepath'
)
->leftjoin('comments', 'comments.comment_to', 'users.id')
->leftjoin('user_portfolios', 'user_portfolios.user_id', 'users.id')
->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
->where('users.status', 1)
->where('users.user_type', 3)
->whereIn('users.id', $portfolio_query_array)
->get();
BTW, why are you doing a leftJoin to user_profile_category_selects if no fields are selected from that table?
In addition, if you are looking for all users that have a portfolio, starting from the whole list of portfolios, wouldn't be better to do a join to portfolios and get only those users having portfolios?
$query = DB::table('users')
->select(
'users.id as user_id',
'users.user_slug',
'users.social_id',
'users.social_img_update_status',
'users.avatar',
'users.first_name',
'users.last_name',
'users.bio',
'comments.rating',
'user_portfolios.title',
'user_portfolios.description',
'user_portfolios.filepath'
)
->leftjoin('comments', 'comments.comment_to', 'users.id')
->join('user_portfolios', 'user_portfolios.user_id', 'users.id')
->leftjoin('user_profile_category_selects', 'user_profile_category_selects.user_id', 'users.id')
->where('users.status', 1)
->where('users.user_type', 3)
->get();
Related
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();
I'm trying to select a number of columns along with MAX. The raw query would be something like: SELECT users.id, ..., MAX(ur.rank) AS rank but I cannot figure out how to do it using the query builder supplied by Laravel in Eloquent.
This is my attempt:
$user = User::join('users_ranks AS ur', function($join) {
$join ->on('ur.uid', '=', 'users.id');
})
->where('users.id', '=', 7)
->groupBy('users.id')
->first(['users.id', 'users.username', 'MAX(ur.rank) AS rank']);
I simply cannot figure it out. What I want to achieve is I'm selecting a user where users.id = 7, and I'm wanting to select the MAX rank that's in users_ranks where their users_ranks.uid = users.id.
I was told to avoid sub-queries as when working with large result sets, it can slow things down dramatically.
Can anyone point me in the right direction? Thanks.
I think you should rewrite it like this:
DB::table('users')
->select(['users.id', 'users.username', DB::raw('MAX(ur.rank) AS rank')])
->leftJoin('users_ranks AS ur', 'ur.uid', '=', 'users.id')
->where('users.id', '=', 7)
->groupBy('users.id')
->first();
No sense to use User:: if you use table names later and want to fetch not all of the fields ( 'users.id', 'users.username' ).
I'm struggling to get unique results when using the DISTINCT method in laravel. This is my query
//Get users that are part of this sector
$users = DB::table('users')->distinct()
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->get();
dd($users);
The result shows 3 users with the same ID, when I only want one of them in the results.
How should I change my query?
Try to use group by id
$users = DB::table('users')
->join('projects', 'users.id', '=', 'projects.userID')
->where('projects.sectorID', '=', $sector->sectorID)
->groupBy('users.id')
->get();
dd($users);
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();
Any way of defining an AS for a query??
I have tried the following:
$data = News::order_by('news.id', 'desc')
->join('categories', 'news.category_id', '=', 'categories.id')
->left_join('users', 'news.user_id', '=', 'users.id') // ['created_by']
->left_join('users', 'news.modified_by', '=', 'users.id') // ['modified_by']
->paginate(30, array('news.title', 'categories.name as categories', 'users.name as username'));
The problem is that ['name'] from categories will be replaces with the one from users. Any way of having them with different names?
Having the aliases above... how can I create an alias where both joins return users.name ?
paginate() method's second parameter accepts array of table columns to select in the query. So this part:
paginate(30, array('news.title, category.name'));
must be like this:
paginate(30, array('news.title', 'category.name'));
UPDATE (after you changed the question)
Try this:
->paginate(30, array('news.title', 'categories.name as category_name', 'users.name as user_name'));
UPDATE 2 (after you changed the question, again)
You can use alias on tables, too:
$data = News::order_by('news.id', 'desc')
->join('categories', 'news.category_id', '=', 'categories.id')
->join('users as u1', 'news.user_id', '=', 'u1.id') // ['created_by']
->join('users as u2', 'news.modified_by', '=', 'u2.id') // ['modified_by']
->paginate(30, array('news.title', 'categories.name as categories', 'u1.name as creater_username', 'u2.name as modifier_username'));
More simple and plain answer to this question is and what I was looking for that Eloquent supports aliases directly with table names or columns, for example:
$users = DB::table('really_long_table_name AS t')
->select('t.id AS uid')
->get();