mardi 11 juillet 2017

Laravel deeply nested relationship query returning incorrect results

So I am working with Laravel 5.4 and have combed stackoverflow and the web for answers to my problem. I am close but something is still not quite right. I am getting MOSTLY valid result sets but they are sprinkled with the odd incorrect record.

Following many suggestions online I am doing the following:

protected function index(Request $request) {
    $orderBy = $request->has('order_by') ? $request->get('order_by') : '';

    $query = Booking::sortable();

    // Limit result set to just the records for this reseller 
    // if the user is a reseller and not a full admin
    if (!empty(\Auth::user()->reseller_id)){
        $query->with(['delivery.delivery_option' => function($subQuery){
            $subQuery->select('reseller_id', \Auth::user()->reseller_id);
        }]);           
    }

    // Determine what query to run based on the selected booking list
    switch ($request->get('type')){
        case 'upcoming':
            $query->doesntHave('named_devices')
                ->orWhere('pickup_date', '>=', date('Y-m-d'));
            break;
        case 'active':
            $query->where('pickup_date', '<=', date('Y-m-d'))
                ->has('named_devices');
            break;
        case 'completed':
            $query->withoutGlobalScope(ActiveBookings::class)->ofState(BookingState::COMPLETE);
            break;
        default:
            break;
    }

    return $query->orderBy($orderBy)->paginate();
}

The problem is with the limiting result set.

$query->with(['delivery.delivery_option' => function($subQuery){
    $subQuery->select('reseller_id', \Auth::user()->reseller_id);
}]);

In a list of roughly 50 results from the DB I have about 6 that are the incorrect reseller_id.

I THINK it has to do with the fact that these results DO have a delivery_option and delivery section, however when I look at the output I can see that reseller_id is incorrect.

Booking Class has this:

public function delivery()
{
    return $this->belongsTo(Delivery::class);
}

Delivery Class has this:

public function delivery_option()
{
    return $this->morphTo(); // delivery_option_type is 'reseller'
}

Delivery Option Class has this:

public function reseller(){
    return $this->hasOne(Reseller::class);
}

Is there any reason this would not be reducing my set properly? Any other suggestions to make this work?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2tLeB75
via IFTTT

Aucun commentaire:

Enregistrer un commentaire