Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all columns which are not in another table laravel 5.5

Tags:

php

mysql

laravel

I have two tables - the first one is called 'users' and the second one is called 'buy_courses'.

users table

enter image description here

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?

like image 842
Rashed Hasan Avatar asked Sep 23 '17 21:09

Rashed Hasan


People also ask

How do you get records which are not in another table in Laravel?

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.

What does get () do in Laravel?

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.

How do I select a column in Laravel?

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.


2 Answers

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();
like image 128
Markownikow Avatar answered Oct 14 '22 04:10

Markownikow


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();
like image 33
anayarojo Avatar answered Oct 14 '22 02:10

anayarojo