laravel-livewire-tables icon indicating copy to clipboard operation
laravel-livewire-tables copied to clipboard

Problems with loading relationships

Open Oleksandr-Moik opened this issue 1 year ago • 2 comments

Case, I have to models - User and Role. User belongsToMany Roles.

And I want to disblay all user roles with this column definition:

Column::make('User roles', 'roles.name')
    ->eagerLoadRelations()
    ->format(function ($roles) {
        return $roles->implode(', ');
    })

Buy I catch an exception: Exception screenshot

During debugging, it turned out that the problem is in determining table name in method WithData::getTableForColumn()

This issue is related pull about Support MorphOne: #844

Also, I think we should add support other relationships types, not only HasOne or BelongsTo

Oleksandr-Moik avatar Aug 11 '22 22:08 Oleksandr-Moik

I have a similar problem. Would also be happy about hasMany support.

fbrettnich avatar Aug 17 '22 10:08 fbrettnich

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Sep 16 '22 10:09 stale[bot]

If anyone has a similar problem and is looking for a solution, here is a small fix or temporary solution (based on my case).

Define column like this:

Column::make('User roles', 'roles')
    ->label(function (User $row): string {
        return $row->roles->pluck('name')->implode(', ');
    })

And add eager roles loading to query builder, to prevent lazy loading for each user row

public function builder(): Builder
{
    return User::query()->with('roles');
}

Oleksandr-Moik avatar Oct 09 '22 16:10 Oleksandr-Moik

Yeah it's a very poor performance way to handle it, you are adding a query for every single row.

If you add it into the Builder method of the component it uses two additional queries. But for some reason that I am unable to figure out, we cannot select the 'AS' value from the with on the query builder because the column builder always references the Parent models table first and 'AS' values will not work.

tonypartridge avatar Oct 21 '22 13:10 tonypartridge

I have the same problem. I selected column with custom join used 'AS' alias and now is not possible to show this alias column in table.

vaskomichal avatar Oct 22 '22 08:10 vaskomichal

Its such a shame, as it is a massive performance increase and something that should be easily catered for, simply not applying table_name before each field would suffix like:

->applyTableNamePrefix(false)

tonypartridge avatar Oct 23 '22 06:10 tonypartridge