orlyapps / nova-belongsto-depend

Larave Nova BelongsTo Field with Dependcy
MIT License
182 stars 65 forks source link

Can't sort by a NovaBelongsToDepend field #55

Closed arad0s closed 4 years ago

arad0s commented 4 years ago

I use the sortable method on a NovaBelongsToDepend:

   NovaBelongsToDepend::make('City')
      ->sortable()
      ->options(\App\City::all()),

But got the following SQL error:

message: "SQLSTATE[42S22]:
Column not found: 1054 Unknown column 'city' in 'order clause'
(SQL: select * from `organizations` order by `city` asc limit 26 offset 0)"

Laravel\Nova\Fields\Field class explicitly handles the BelongsTo field case when sorting:

    /**
     * Return the sortable uri key for the field.
     *
     * @return string
     */
    public function sortableUriKey()
    {
        $request = app(NovaRequest::class);

        switch (get_class($this)) {
            case BelongsTo::class:
                return $this->getRelationForeignKeyName($request->newResource()->resource->{$this->attribute}());
            default:
                return $this->attribute;
        }
    }

So the solution seems to be overriding the sortableUriKey method as follows on Orlyapps\NovaBelongsToDepend\NovaBelongsToDepend:

    /**
     * Return the sortable uri key for the field.
     *
     * @return string
     */
    public function sortableUriKey()
    {
        $request = app(NovaRequest::class);

        return $this->getRelationForeignKeyName($request->newResource()->resource->{$this->attribute}());
    }

It worked for me when modified the NovaBelongsToDepend class temporarily on my vendor.

Waiting for the bug fix.

orlyapps commented 4 years ago

fixed in 9e6e8a4769813c593d50115968321e0d1f220ebb