Laravel Eloquent three tables query
I'm not able to take out all tasks for the user which is logged in.
I have three tables but i'm finding it hard to make the Eloquent statement to fetch data.
Below are the tables with data:
Tasks
| id | task_name |task_desc |
| ------------- | ------------- |------------- |
| 1 | test 123 | description |
| 2 | test234 | desnjnll |
Users
id | username
---|---------------
1 | kaushik
Workers
id | task_id | user_id
---|----------|--------------
1 | 1 | 1
1 | 2 | 1
You could create a hasManyThrough relation in your User model.
It would look like this I guess.
// User.php
public function tasks()
{
return $this->hasManyThrough(Task::class, Worker::class);
}
Then you would use something like auth()->user()->tasks.
@depsimon No, this is not a double has many (workers table working as a pivot table).
@djkaushiksk1 this is a hasAndBelongsToMany relationship with workers as a pivot table. Check the docs.
Yep its not working.
That's why i need help on this. Can any one help me out on this
Oh right, then I suppose that a simple belongsToMany should do the trick here.
// User.php
public function tasks()
{
return $this->belongsToMany(Task::class, 'workers');
}
Please or to participate in this conversation.