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...
@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
I already did that, for another thing though, but I'm not sure how to get users that don't have jobs?
$users = Users::doesnthave('jobs')->get();
$users = DB::table('users')
->join('jobs', 'users.id', '!=', 'jobs.user_id')
->get();
@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'?
@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?
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...
@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();
$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...
@shone83 Np, we all around here to help
Happy coding!
Please sign in or create an account to participate in this conversation.