I have two tables - the first one is called 'users' and the second one is called 'buy_courses'.
I am trying to select all users those user_name is not in buy_courses. I tried something like -
$users = DB::table('users')
->rightjoin('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
It returns all users, whose user_name is in 'buy_courses', when I am using '<>', then I'm getting all users. What should be the right query?
We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
For creating ::where statements, you will use get() and first() methods. The first() method will return only one record, while the get() method will return an array of records that you can loop over. Also, the find() method can be used with an array of primary keys, which will return a collection of matching records.
Select specific columns with Laravel Eloquent To get all of the columns from the users table, we would use the following: $user = User::where('username', 'bobbyiliev')->get(); However, if you wanted to get only a specific column, you could pass it as an argument to the get() method.
DB::table("users")->select('*')->whereNotIn('user_name',function($query) {
$query->select('user_name')->from('buy_courses');
})->get();
just join actually is inner join in Laravel so actually maybe also you can try:
DB::table('users')
->join('buy_courses', 'users.user_name', '=', 'buy_courses.user_name')
->get();
Try it using Eloquent:
$courseUserNames = BuyCourses::pluck('user_name')->all();
$users = User::whereNotIn('user_name', $courseUserNames)->select(...)->get();
Or if you prefer using DB query:
$courseUserNames = DB::table('buy_courses')->pluck('user_name')->all();
$users = DB::table('users')->whereNotIn('user_name', $courseUserNames)->select(...)->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With