我有一个简单的 laravel 应用程序(我认为结构):表格: 位置 id [...]
售票 地点_id 登机口_日期 售票数量
我有以下模型:
class Location extends Model
{
use HasFactory;
protected $table = 'locations';
protected $primaryKey = 'id';
protected $fillable = [
...
];
public function ticketSales(): HasMany
{
return $this->hasMany(Ticketsales::class, 'location_id', 'id')
->where('deleted', 0);
}
}
和
class TicketSales extends Model
{
use HasFactory;
protected $table = 'ticket_sales';
protected $primaryKey = 'id';
protected $fillable = [
...
];
public function location(): BelongsTo
{
return $this->belongsTo(Location::class, 'location_id', 'id');
}
}
销售是基于日期的,我正在尝试编写一个范围,它接受一个日期参数并返回该日期之前地点的最新销售情况。
我已经创建了一个函数来显示我想要使用的逻辑,我只是不确定如何将其变成范围以便可以轻松使用它:
public function latestSalesAtDate($effective_date): HasOne
{
$carbon_date = Carbon::parse($effective_date);
return $this->hasOne(TicketSales::class)->ofMany([
'gate_date' => 'max',
'id' => 'max',
], function (Builder $query) use ($effective_date) {
$query->where('gate_date', '<=', $effective_date);
});
}
例如,如果我有以下数据:
Locations
id=1
id=2
id=3
TicketSales
location_id=1, gate_date='2024-01-01', number_tickets_sold=100
location_id=1, gate_date='2024-01-02', number_tickets_sold=200
location_id=1, gate_date='2024-01-03', number_tickets_sold=300
location_id=1, gate_date='2024-01-04', number_tickets_sold=400
location_id=2, gate_date='2024-01-01', number_tickets_sold=102
location_id=2, gate_date='2024-01-02', number_tickets_sold=202
location_id=2, gate_date='2024-01-05', number_tickets_sold=302
location_id=2, gate_date='2024-01-06', number_tickets_sold=402
location_id=3, gate_date='2024-01-01', number_tickets_sold=103
location_id=3, gate_date='2024-01-02', number_tickets_sold=203
location_id=3, gate_date='2024-01-08', number_tickets_sold=303
location_id=3, gate_date='2024-01-09', number_tickets_sold=403
我想要
$locations = Location::withLatestSalesAtDate('2024-01-05')->get();
返回所有地点的列表,以及每个地点的最新销售记录
地点 id=1, gate_date='2024-01-04', number_tickets_sold=400
地点 id=2, gate_date='2024-01-05', number_tickets_sold=302
地点 id=3, gate_date='2024-01-02', number_tickets_sold=203
我该如何定义这个范围?