您好我在我的项目中使用Eloquent和Slim。我创建了模型:Reservation,ReservationCottage(链接表),带关系的Cottage:预订N-N等小屋,现在我想知道如何更改我的SQL查询以查找Eloquent查询。
class Reservation extends Model
{
protected $table = 'reservations';
protected $fillable = [
'start',
'end',
];
public function cottages()
{
return $this->belongsToMany(Cottage::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function reservationStatus()
{
return $this->belongsTo(ReservationStatus::class);
}
public function payments()
{
return $this->hasMany(Payment::class);
}
}
class ReservationCottage extends Model
{
protected $table = 'reservation_cottages';
public function guests()
{
return $this->hasMany(Guest::class);
}
}
class Cottage extends Model
{
protected $table = 'cottages';
protected $fillable = [
'name',
'capacity',
'description',
'base_price',
];
public function additions()
{
return $this->belongsToMany(Addition::class);
}
public function cottagePeriods()
{
return $this->hasMany(CottagePeriod::class);
}
public function periods()
{
return $this->belongsToMany(Period::class);
}
public function reservations()
{
return $this->belongsToMany(Reservation::class);
}
public function cottageStatus()
{
return $this->belongsTo(CottageStatus::class);
}
这是查询wchih检查预订表中是否有句点(从@ArrivalDate
到@DepartureDate
):
SELECT cottage.name FROM cottages WHERE id NOT IN (
SELECT cottage_id
FROM reservation_cottages RC
JOIN reservations R
ON R.id = RC.reservation_id
WHERE (r.start <= @ArrivalDate AND R.end >= @ArrivalDate)
OR (R.start < @DepartureDate AND R.end >= @DepartureDate )
OR (@ArrivalDate <= R.start AND @DepartureDate >= R.start)
答案 0 :(得分:0)
好的,这是一个(希望)更有帮助的答案。在我的示例中,我使用Laravel Query Builder来创建这样一个复杂的查询。例如:
$rows = DB::table('cottages')
->select('cottage.name')
->from('cottages')
->whereNotIn('id', function (Builder $query) {
$query->select('cottage_id')
->from('reservation_cottages AS RC')
->join('reservations AS R', 'R.id', '=', 'RC.reservation_id')
->whereColumn('r.start', '<=', 'ArrivalDate')
->whereColumn('R.end', '>=', 'ArrivalDate')
->orWhere(function (Builder $query) {
$query->whereColumn('R.start', '<', 'DepartureDate')
->whereColumn('R.end', '>=', 'DepartureDate');
})
->orWhere(function (Builder $query) {
$query->whereColumn('ArrivalDate', '<=', 'R.start')
->whereColumn('DepartureDate', '>=', 'R.start');
});
})->get();
生成的SQL:
SELECT
`cottage`.`name`
FROM
`cottages`
WHERE `id` NOT IN
(SELECT
`cottage_id`
FROM
`reservation_cottages` AS `RC`
INNER JOIN `reservations` AS `R` ON `R`.`id` = `RC`.`reservation_id`
WHERE `r`.`start` <= `ArrivalDate`
AND `R`.`end` >= `ArrivalDate`
OR (
`R`.`start` < `DepartureDate`
AND `R`.`end` >= `DepartureDate`
)
OR (
`ArrivalDate` <= `R`.`start`
AND `DepartureDate` >= `R`.`start`
));