Aug 4, 2021
0
Level 1
Eloquent problem
I am trying to make a query that will select apartments that are not in the given date range. The apartments have reservations. The problem is that the apartment does not show up when all booking records are in this range, but shows available when the given date range is between reservation date range.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Aparts extends Model
{
use HasFactory;
public function reservations(){
return $this->hasMany(Reservations::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Reservations extends Model
{
use HasFactory;
public function aparts(){
return $this->belongsTo(Aparts::class);
}
}
So, when the Apartament 1 has reservations :
- 2021-08-01 - 2021-08-5
- 2021-08-10 - 2021-08-15
$aparts = Aparts::whereHas('reservations', function($q) use($startstr,$endstr){
$q->whereNotBetween('datestart',[$startstr,$endstr])
->whereNotBetween('dateend',[$startstr,$endstr])
->orWhere('datestart','>=',$endstr)
->where('dateend','<=',$startstr);
})->orWhereDoesntHave('reservations');
And the given range is : 2021-08-01 - 2021-08-03 the Apartament 1 shows as available becouse reservation 2 wasnt in range. How to beat that? I know that apartment 1 shows as available ex. by that:
->orWhere('datestart','>=',$endstr)
Please or to participate in this conversation.