Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Order By on Relatable Query #1484

Closed
JordanDinsdale opened this issue Mar 29, 2019 · 26 comments
Closed

Order By on Relatable Query #1484

JordanDinsdale opened this issue Mar 29, 2019 · 26 comments
Labels
implemented Feature Request implemented request Feature Request
Milestone

Comments

@JordanDinsdale
Copy link

JordanDinsdale commented Mar 29, 2019

Hi, I need to apply an order on a relatable query in Laravel Nova.

I've tried everything on this page #156 and can't get any of the methods detailed to work with my application.

I have 3 models significant to this problem; Event, Brand and Vehicle.

Events Belong To Many Brands | Brands Belong To Many Events
Brand Has Many Vehicles | Vehicles Belong To a Brand
Event Belongs To Many Vehicles | Vehicles Belong To Many Events

When a user creates an Event, they then go on to choose Brands associated with that Event.

This is facilitated by putting the below line in the fields function in my Nova Event Resource.

BelongsToMany::make('Brand')->sortable(),

Once a user has attached associated Brands, they then go on to attach associated Vehicles.

The list of Vehicles is populated using a relatable query that I have in my Nova Event Resource;

public static function relatableVehicles(NovaRequest $request, $query)
{

    $event = $request->findResourceOrFail();

    $brand_ids = [];

    foreach($event->brand as $brand) {
        $brand_ids[] = $brand['id'];
    }

    return $query->whereIn('brand_id', $brand_ids);

}

Now when I go to attach a Vehicle, it is populated only by Vehicles that are related to the Brands attached to the Event.

The problem is that the options in the select box provided are ordered by the title.

I have the below in my Vehicle resource, which I think is where the problem stems from;

public static $title = 'model';

But obviously I need that in the Resource so that the select box displays appropriately.

Does anyone know how I can order by something other than title instead? I'm trying to order by brand_id.

@JordanDinsdale JordanDinsdale changed the title Order By on Releatable Query Order By on Relatable Query Apr 1, 2019
@devfrey
Copy link

devfrey commented Apr 3, 2019

What's wrong with applying an orderBy to the query in your relatable query? That should work, really.

@JordanDinsdale
Copy link
Author

JordanDinsdale commented Apr 3, 2019

It doesn't.

I've tried changing the above code to;

public static function relatableVehicles(NovaRequest $request, $query)
    {

        $event = $request->findResourceOrFail();

        $brand_ids = [];

        foreach($event->brands as $brand) {
            $brand_ids[] = $brand['id'];
        }

        return $query->whereIn('brand_id', $brand_ids)->orderBy('brand_id','asc');

    }

I also changed public static $title = 'model';

to

public function title() { return $this->model . ' - ' . $this->brand_id; }

just to illustrate how it isn't working. I've attached the result below;

Screen Shot 2019-04-03 at 17 36 39

@christophrumpel
Copy link

Anything new here? I'm facing the same problem.: orderBy() is not working when overriding the relatableQuery method. I guess the order from there is being overwritten later?

Also tried to override the applyOrderings method, but still no ordering.

@christophrumpel
Copy link

@dillingham showed me that the order is set in the AttachableController. So setting the order inside the relatableQuery method does not work =/ I'm also looking for a solution since this is very important for my client. Haven't found a good one yet.

@jbrooksuk
Copy link
Member

This issue relates to an older version of Nova. It's possible that this bug has been fixed in recent versions. If you're still experiencing this in the latest version of Nova, please re-open this ticket, thanks!

@robin-dongbin
Copy link

robin-dongbin commented Sep 2, 2019

Have same issue.I think it's because of Nova re-sorted related resource by hard code.

See

Laravel\Nova\Http\Controllers\AssociatableController

 public function index(NovaRequest $request)
    {
        $field = $request->newResource()
                    ->availableFields($request)
                    ->firstWhere('attribute', $request->field);

        $withTrashed = $this->shouldIncludeTrashed(
            $request, $associatedResource = $field->resourceClass
        );

        return [
            'resources' => $field->buildAssociatableQuery($request, $withTrashed)->get()
                        ->mapInto($field->resourceClass)
                        ->filter->authorizedToAdd($request, $request->model())
                        ->map(function ($resource) use ($request, $field) {
                            return $field->formatAssociatableResource($request, $resource);
                        })->sortBy('display')->values(),
            'softDeletes' => $associatedResource::softDeletes(),
            'withTrashed' => $withTrashed,
        ];
    }

@lab08tonci
Copy link

@JordanDinsdale, Can you reopen this bug, as it is still valid at the latest Nova version (v2.6.1)
The reason is what @winter-ice have stated in the previous comment.

The order is hardcoded and no mater what we do, it will not change.

@JordanDinsdale
Copy link
Author

This issue relates to an older version of Nova. It's possible that this bug has been fixed in recent versions. If you're still experiencing this in the latest version of Nova, please re-open this ticket, thanks!

Hi, I don't really think "It's possible that this bug has been fixed in recent versions" is a good enough reason to close a ticket that's occuring in software that has been bought and paid for.

Why didn't you check if it had been fixed, then report back...?

@lab08tonci, @jbrooksuk, or anyone else;
How do I reopen a ticket? This thread seems to suggest I can't...
isaacs/github#583

@jbrooksuk
Copy link
Member

@JordanDinsdale we get a lot of tickets and they take a lot of time. Help us, help you.

@JordanDinsdale
Copy link
Author

@JordanDinsdale we get a lot of tickets and they take a lot of time. Help us, help you.

I am really trying, but people are closing tickets without good reason, and not telling me how I can reopen them when asked... What exactly is it that you're suggesting I should do about these things?

@jbrooksuk
Copy link
Member

@JordanDinsdale until you said that you were unable to reopen the issue, I was unaware that it was the case. We reserve the right to manage the issues at our discretion. As with all tickets, we're always reading them and keeping an eye on them.

@jbrooksuk jbrooksuk reopened this Nov 15, 2019
@JordanDinsdale
Copy link
Author

@jbrooksuk Thanks James, I look forward to seeing what progress you can make regarding this

@reppair
Copy link

reppair commented Dec 4, 2019

Yeah, I also can't apply my custom sortBy to the relatable query.. :(

@jbrooksuk jbrooksuk added this to the v2.x milestone Dec 4, 2019
@schakko
Copy link

schakko commented Jan 24, 2020

Quick fix

As a quick fix I am doing the following:

  1. Copy nova\src\Http\Controllers\AttachableController.php to app\Http\Controllers\Nova\AttachableController.php, don't forget to update the namespace of the copied AttachableController
  2. Simply remove the sortBy statement in app\Http\Controllers\Nova\AttachableController.php:
        return [
            'resources' => $field->buildAttachableQuery($request, $withTrashed)->get()
                        ->mapInto($field->resourceClass)
                        ->filter(function ($resource) use ($request, $parentResource) {
                            return $parentResource->authorizedToAttach($request, $resource->resource);
                        })
                        ->map(function ($resource) use ($request, $field) {
                            return $field->formatAttachableResource($request, $resource);
                        })

                // ignore Laravel's Collecting::sortBy, @see https://github.com/laravel/nova-issues/issues/1484
                //->sortBy('display', SORT_NATURAL | SORT_FLAG_CASE)
                ->values(),
            'withTrashed' => $withTrashed,
            'softDeletes' => $associatedResource::softDeletes(),
        ];
  1. In your app\Providers\NovaServiceProvider.php, set an alias for your own AttachableController:
class NovaServiceProvider extends NovaApplicationServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        parent::boot();

        // map Nova's AttachableController to our own instnace
        $this->app->alias(
            \App\Http\Controllers\Nova\AttachableController::class,
            \Laravel\Nova\Http\Controllers\AttachableController::class
        );
    }
}
  1. In your relatableQuery, define the sorting columns:
    public static function relatableQuery(NovaRequest $request, $query) {
        $query->getQuery()->orders = [['column' => 'type', 'direction' => 'asc'], ['column' => 'name', 'direction'  => 'asc']];

        return $query;
    }

Possible long term fix

As a reasonable fix I suggest to wrap the

$field->buildMorphableQuery() 

into a fascade like

MorphableCollection::sort($field->buildMorphableQuery()....)

and

AssociatableCollection::sort($field->buildMorphableQuery()....)

The developer can either use the default sorting algorithm (sortBy('display')) or overwrite the sorting algorithm.

@elijahworkz
Copy link

elijahworkz commented Feb 17, 2020

This issue still exists (Nova 2.9.4)
adding ->orderBy() makes no difference and in my case - creates an error of ambiguous column name

I'm trying to create a filter by altering query in apply method:
return $query->join('campaigns', 'campaigns.id', '=', 'campaign_id')->where('campaigns.brand_id', $value)->orderBy('pages.id');
This makes no difference and i still get an error.

It looks like the filter query is wrapped in applyOrderings method from PerformsQueries trait.
applyOrderings only works for the order specified on the model itself and ignores orderBy set by the filter.

@tushar-kharmate
Copy link

Hello @jbrooksuk, This issue still exists in Nova v3.6.

public static function relatableQuery(NovaRequest $request, $query) { return $query->orderBy('sort_order','asc'); }

Can you Provide any updates on this issue? It will be helpful.

@stale
Copy link

stale bot commented Jul 25, 2020

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 stale bot added the stale label Jul 25, 2020
@jbrooksuk jbrooksuk added the request Feature Request label Jul 27, 2020
@stale stale bot removed the stale label Jul 27, 2020
@jbrooksuk
Copy link
Member

Sorry for the lack of updates.

In order to keep this repository focused on bug reports, we auto-close feature requests and requests for help. Feel free to post your feature requests so others can discuss and add reactions. We'll keep an eye on them for later planning.

@joselara
Copy link

Hey can we get an update on sorting relatable queries. I don't think it's a new feature but a bug. Thanks.

@wizard0822

This comment has been minimized.

@flatcapco
Copy link

Is there any progress on this bug please?

@reppair
Copy link

reppair commented May 24, 2021

I could get rid of all the custom BS queries I've wrote in order to achieve my sorting in several resources.. getting used to it. :)

@crynobone
Copy link
Member

https://nova.laravel.com/docs/3.0/resources/relationships.html#disable-ordering-by-title

@crynobone crynobone added the implemented Feature Request implemented label Jun 9, 2021
@reppair
Copy link

reppair commented Jun 9, 2021

https://nova.laravel.com/docs/3.0/resources/relationships.html#disable-ordering-by-title

Hi @crynobone, seems like there is no #disable-ordering-by-title section on that page.

@crynobone
Copy link
Member

Screenshot_20210609-181953.jpg

@github-actions
Copy link

github-actions bot commented Oct 6, 2021

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Oct 6, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
implemented Feature Request implemented request Feature Request
Projects
None yet
Development

No branches or pull requests