Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shone83's avatar

How to get list from one table that has not relations from another?

If I have user table like this:

| id | name | 
| --- | --- | 
| 1 | John | 
| 2 | Michael | 
| 3 | Jane |

and table like this:

| id | user_id | jobs | 
| --- | --- | --- | 
| 1 | 1 | something | 
| 2 | 1 | something | 
| 3 | 1 | something | 
| 4 | 3 | something | 
| 5 | 3 | something |

how to make table where would be only John and Jane, but no Michael because his ID is not in second table?

p.s. I read this: https://help.github.com/articles/organizing-information-with-tables/ but tables here seems not working...

0 likes
10 replies
Dhaval_patel's avatar

@shone83 You can simply write two models along with one to many relationship in your case there would be one user model having

class user extends Model
{
   public function jobs()
    {
        return $this->hasMany('App\jobs');
    }
}

and then you can insert those records in new table.

Hope that helps

1 like
shone83's avatar

I already did that, for another thing though, but I'm not sure how to get users that don't have jobs?

Sirik's avatar
Sirik
Best Answer
Level 11
$users = Users::doesnthave('jobs')->get();
2 likes
Dhaval_patel's avatar
$users = DB::table('users')
            ->join('jobs', 'users.id', '!=', 'jobs.user_id')
            ->get();
1 like
shone83's avatar

@Sirik

That returns all with jobs, not without.

@Dhaval_patel

That returns nothing. Is 'jobs' in join function name of the table or method? And why 'users (dot) id'?

Dhaval_patel's avatar

@shone83 That is what how you joins the table in SQL, here is the syntax

SELECT columns FROM table1 
INNER JOIN table2 ON table1.column = table2.column;

In your case you want record of michael which is not present in another table. You do not know how to write join queries in mysql?

1 like
shone83's avatar

I'm not sure why I need to join tables in the first place. I thought that laravel have some method that get what's missing from table with relations. Either way this is not working for me or I didn't understand you...

Dhaval_patel's avatar

@shone83 if you have not use models use query builder

$users = DB::table('users')
            ->join('jobs', 'users.id', '!=', 'jobs.user_id')
            ->get();

or if you have wrote models $users = Users::doesntHave('jobs')->get();

1 like
shone83's avatar
$users = Users::doesntHave('jobs')->get();

This do the trick. Thanks @Dhaval_patel

Now I see that @Sirik first show me this but I didn't see, or he update answer later...

Please or to participate in this conversation.