Jeffery has a video that might be helpful: https://laracasts.com/series/eloquent-relationships/episodes/4
How to do hasManyThrough() query??
Hi, so I am trying to retrieve data using the hasManyThrough() relationship and at this point I am able to get a response but the data is missing. Im not sure if it is including the client_id to grab the correct client from the table but im looking for any suggestions. Thanks.
My relationships are
- Engagement belongsTo Client
- Client hasMany Engagements
- Task belongsTo User
- User hasMany Tasks
- Tasks belongsToMany Engagements and of course vise versa.
I have a engagement_task pivot table storing the task_id and engagement_id
Now I referenced this article to get going with it link
However mine still looks different, although it is the closest I have gotten to retrieving everything
When I try to mimic the article I will get alarm. If you want to see that let me know or if you have a better suggestion all together let me know..
I will include image at bottom showing what I am currently getting
here is the Pivot model
<?php
namespace App\Pivots;
use Illuminate\Database\Eloquent\Relations\Pivot;
class EngagementTask extends Pivot {
public function client()
{
return $this->hasManyThrough('App\Client', 'App\Engagement');
}
}
here is the Task model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $fillable =
[
'user_id',
];
public function user() {
return $this->belongsTo('App\User');
}
public function engagements()
{
return $this->belongsToMany('App\Engagement', 'engagement_task', 'task_id', 'engagement_id');
}
public function client()
{
return $this->hasManyThrough('App\Client', 'App\Pivots\EngagementTask', 'engagement_id', 'id', 'id', 'engagement_id');
}
}
And here is the TasksController that I am using to make the query
public function index()
{
return Task::where('user_id', auth()->user()->id)->with(['engagements', 'client'])->get();
}
*embed didn't work
@impbob, well for my use case I actually didn't have to use the hasManyThrough() method at all.
I just did this
public function index()
{
return Task::where('user_id', auth()->user()->id)->with(['engagements', 'engagements.client'])->get();
}
Adding the engagements.client did the trick.
I found the solution here
Please or to participate in this conversation.