Home > Mobile >  Property does not exist on this collection instance when fetching from related models
Property does not exist on this collection instance when fetching from related models

Time:02-26

I have this query which return data from one table :

$existData =Booking::where(function ($query)use($start, $end){
                                    $query->whereBetween('start', [
                                        $start, $end
                                    ])->orwhereBetween('end', [
                                        $start, $end]);
                                })->where('status','confirmed')->get();

this returns data but when i add relation to it

$existData =Booking::where(function ($query)use($start, $end){
                                        $query->whereBetween('start', [
                                            $start, $end
                                        ])->orwhereBetween('end', [
                                            $start, $end]);
                                    })->where('status','confirmed')->with(['bookingDetails'=> function ($q) use($data){
                                    $q->where('user_type',$data->type);
                      
                                }])->get();

It gives error :

Property [user_type] does not exist on this collection instance.

but i have created relation in Booking model

public function bookingDetails()
    {
        return $this->hasMany('App\Models\BookingRoomDetails', 'o_id', 'id');
    }

BookingDetailModel :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BookingRoomDetails extends Model
{
    use HasFactory;
}

I want this whole query should only return data if outer query and inner query returns true eg. $q->where('user_type',$utype->type); and the time range exist which is already working fine.

Any solution to resolve this issue

CodePudding user response:

Change the query code like:

use Illuminate\Database\Eloquent\Builder;

$existData = Booking::with(['bookingDetails'=> function ($q) use ($data) {
    $q->where('user_type',$data->type);
}])->where(function (Builder $query) use ($start, $end) {
    return $query->whereBetween('start', [ $start, $end ])
        ->orwhereBetween('end', [ $start, $end ]);
})->where('status','confirmed')
->get();
  • Related