Reputation: 11368
I'm trying to eager load some data through an id in a pivot table.
Right now I've just done it manually but wondering if there is a way to do this directly through eloquent with a relation?
$ids = $tournament->matches
->pluck('users')
->flatten()
->pluck('pivot')
->pluck('team_id')
->unique();
$teams = \App\Models\Team::whereIn('id', $ids)->get()->keyBy('id');
$tournament->matches->each(function ($match) use ($teams) {
$match->users->each(function ($user) use ($teams) {
$user->team = @$teams[$user->pivot->team_id] ?: null;
});
});
Upvotes: 0
Views: 1904
Reputation: 4321
you can return the instance of Pivot which extends the Model ultimately. so for ex. in tournament has belongs to many team relation then in tournament model
/**
* @param Model $parent
* @param array $attributes
* @param string $table
* @param bool $exists
* @return ProjectTeamPivot
*/
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
return new TeamPivot($parent, $attributes, $table, $exists);
}
and in your team pivot class goes as below
use Illuminate\Database\Eloquent\Relations\Pivot;
class TeamPivot extends Pivot
{
/**
* @var array
*/
protected $fillable = [];
protected $casts = [];
// this is the instance of model itself which represents the intermediate table so you can define any kind of relation as you would define in normal model load it eagerly like
protected $with = []; // you can always load a model if you fill the relation name in this array
}
for more information head over to here https://softonsofa.com/laravel-custom-pivot-model-in-eloquent/
Upvotes: 2