简体   繁体   中英

relatableQuery() for two resource fields on same model in Laravel Nova

I have a relationship between work 'days' and projects of different types. So my 'days' record has a reference to my 'projects' table twice because I have two different types of projects called 'Series' and 'Event'.

In my 'days' resource I've created two fields as such:

BelongsTo::make('Series','series',Project::class)->sortable()->nullable(),
BelongsTo::make('Event','event',Project::class)->sortable()->nullable(),

What I'm trying to do is filter the projects by their types so I've created this:

public static function relatableProjects(NovaRequest $request, $query){
    return $query->where('type', 'Series');
}

I've tried making relatableSeries and relatableEvents but they don't work. How can I make this connect to the fields correctly without having to create two separate tables for 'series' and 'events'.

The relatableQuery above winds up filtering both resource fields.

Because relatableQuery() is referencing a relatableModel() (so relatableProjects() references the Project model) I was able to create another model solely for the purpose of helping with this.

I created an Event model which references the same projects table and then was able to create a relatableEvents() method to use the where() filter query.

Note: I did have to also create an Event resource which references the Event model since this is how Nova works but was able to hide it from being accessed which you can find more information about here

See revised BelongsTo fields and new model below:

Day resource

    /**
     * Build a "relatable" query for the given resource.
     *
     * This query determines which instances of the model may be attached to other resources.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function relatableProjects(NovaRequest $request, $query){
        return $query->where('type', 'Series');
    }

    /**
     * Build a "relatable" query for the given resource.
     *
     * This query determines which instances of the model may be attached to other resources.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function relatableEvents(NovaRequest $request, $query){
        return $query->where('type', 'Event');
    }

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->hideFromIndex()->hideFromDetail()->hideWhenUpdating(),
            BelongsTo::make('User','user',User::class)->sortable(),
            BelongsTo::make('Budget','budget',Budget::class)->sortable()->nullable(),
            BelongsTo::make('Series','series',Project::class)->sortable()->nullable(),
            BelongsTo::make('Event','event',Event::class)->sortable()->nullable(),
            DateTime::make('Last Updated','updated_at')->hideFromIndex()->readOnly(),
            new Panel('Schedule',$this->schedule()),
            new Panel('Time Entry',$this->timeEntries()),

        ];
    }

Event model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'projects';

    protected $casts = [
        'starts_on' => 'date',
        'ends_on' => 'date',
    ];

    public function event(){
        return $this->belongsTo('App\Event');
    }

    public function project(){
        return $this->belongsTo('App\Project');
    }
}

i know it is an old question but i was facing same problem with laravel nova belongsto field, in some resource i have a belongsto that relates to users but these should be of 'supervisor' role in another resource i hace a belongsto field relating to users but these should be of role 'guard', as laravel nova belongsto field just takes all users in both selects all users appeared and it seems nova belongsto field doe not have a way, or at least i did not find it to scope the query, so what i did was creating a php class named BelongstoScoped this class extends laravle nova field BelongsTo so i overwrote the method responsible of creating the query

<?php

namespace App\Nova\Customized;

use Laravel\Nova\Query\Builder;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Http\Requests\NovaRequest;

class BelongsToScoped extends BelongsTo
{

    private  $modelScopes = [];

    //original function in laravel belongsto field
    public function buildAssociatableQuery(NovaRequest $request, $withTrashed = false)
    {
        $model = forward_static_call(
            [$resourceClass = $this->resourceClass, 'newModel']
        );

        $query = new Builder($resourceClass);
        
        //here i chaned this:
        /*
        $query->search(
                                $request,  $model->newQuery(), $request->search,
                                [], [], ''
                          );
        */
        //To this:
        /*
        $query->search(
                                $request,  $this->addScopesToQuery($model->newQuery()), $request->search,
                                [], [], ''
                          );
        */
        //The method search receives a query builder as second parameter, i just passed the result of custom function 
        //addScopesToQuery as second parameter, thi method returns the same query but with the model scopes passed

        $request->first === 'true'
                        ? $query->whereKey($model->newQueryWithoutScopes(), $request->current)
                        : $query->search(
                                $request,  $this->addScopesToQuery($model->newQuery()), $request->search,
                                [], [], ''
                          );

        return $query->tap(function ($query) use ($request, $model) {
            forward_static_call($this->associatableQueryCallable($request, $model), $request, $query, $this);
        });
    }

    //this method reads the property $modelScopes and adds them to the query
    private function addScopesToQuery($query){
        foreach($this->modelScopes as $scope){
            $query->$scope();
        }
        return $query;
    }

    // this method should be chained tho the field 
    //example: BelongsToScoped::make('Supervisores', 'supervisor', 'App\Nova\Users')->scopes(['supervisor', 'active'])
    public function scopes(Array $modelScopes){

        $this->modelScopes = $modelScopes;
        return $this;

    }

}

?>

In my users model i have the scopes for supervisors and guard roles like this:

public function scopeActive($query)
    {
        return $query->where('state', 1);
    }

    public function scopeSupervisor($query)
    {
        return $query->role('supervisor');
    }

    public function scopeSuperadmin($query)
    {
        return $query->role('superadmin');
    }

    public function scopeGuarda($query)
    {
        return $query->role('guarda');
    }

So in the laravel nova resource i just included the use of this class *remember the namespace depends on how you name your file, in my case i created the folder Customized and included the file there:

use App\Nova\Customized\BelongsToScoped;

In the fields in nova resource i used like this:

BelongsToScoped::make('Supervisor', 'supervisorUser', 'App\Nova\Users\User')
                            ->scopes(['supervisor', 'active'])
                            ->searchable()

So that way i could call the belongsto field in the nova resources which filter users depending on modle scopes.

I hope this helps someone, sorry if my English is not that good.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM