how to eager load in relationship manager

i have these models
class Company extends Model
{
public function events(): BelongsToMany
{
return $this->belongsToMany(Event::class)
->using(CompanyEvent::class)
->as('events')
->withPivot([
'profile_id'
]);
}

public function profiles(): HasMany
{
return $this->hasMany(CompanyProfile::class);
}
}

class Event extends Model
{
public function companies(): BelongsToMany
{
return $this->belongsToMany(Company::class)
->as('companies')
->using(CompanyEvent::class)
->withPivot([
'profile_id',
]);
}
}

class CompanyEvent extends Pivot
{
protected $fillable = [
'company_id', 'event_id', 'profile_id',
];

public function profile(): BelongsTo
{
return $this->belongsTo(CompanyProfile::class);
}
}
class Company extends Model
{
public function events(): BelongsToMany
{
return $this->belongsToMany(Event::class)
->using(CompanyEvent::class)
->as('events')
->withPivot([
'profile_id'
]);
}

public function profiles(): HasMany
{
return $this->hasMany(CompanyProfile::class);
}
}

class Event extends Model
{
public function companies(): BelongsToMany
{
return $this->belongsToMany(Company::class)
->as('companies')
->using(CompanyEvent::class)
->withPivot([
'profile_id',
]);
}
}

class CompanyEvent extends Pivot
{
protected $fillable = [
'company_id', 'event_id', 'profile_id',
];

public function profile(): BelongsTo
{
return $this->belongsTo(CompanyProfile::class);
}
}
the company_event table is unique by 3 columns now in my EventResource->CompaniesRelationManager, I would want to display the profile name, i tried Tables\Columns\TextColumn::make('companies.profile.name'), while it works it is having N+1
4 Replies
Noxo
Noxo16mo ago
try to add eager load to your CompaniesRelationManager
public function table(Table $table) : Table
{
return $table
->modifyQueryUsing(fn (Builder $query) => $query->with('profile'))
public function table(Table $table) : Table
{
return $table
->modifyQueryUsing(fn (Builder $query) => $query->with('profile'))
wyChoong
wyChoongOP16mo ago
nope that doesnt work for me
Noxo
Noxo16mo ago
hmm, maybe this one ->with('companies.profile')
wyChoong
wyChoongOP16mo ago
table
->modifyQueryUsing(fn ($query) => $query->with('profiles'))
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('profile_id')
->formatStateUsing(fn ($state, $record) => $record->profiles->where('id', $state)->first()?->name)
])
table
->modifyQueryUsing(fn ($query) => $query->with('profiles'))
->columns([
Tables\Columns\TextColumn::make('name'),
Tables\Columns\TextColumn::make('profile_id')
->formatStateUsing(fn ($state, $record) => $record->profiles->where('id', $state)->first()?->name)
])
using this now, seems good for now thanks
Want results from more Discord servers?
Add your server