我正在尝试根据可用期获取过期列表,有 3 个不同的可用期。只有当该行的最新非空 to_date_* 早于现在时,才应返回该行。
示例数据:
我的 SQL 查询是:
$listings = collect();
$all_listings = Listing::query()
->where('vendor_id', $vendor->id)
->where('is_deleted', 0)
->where('is_published', 1)
->where('is_approved', 1)
->where('lease_term', '!=', 'long_term')
->orderBy('created_at', 'desc')
->paginate(10);
foreach($all_listings as $lis)
{
if($lis->to_date_3 != null && ($lis->to_date_3 < \Carbon\Carbon::now()->format('Y-m-d')))
{
$listings->add($lis);
continue;
}
elseif($lis->to_date_2 != null && ($lis->to_date_2 < \Carbon\Carbon::now()->format('Y-m-d')))
{
$listings->add($lis);
continue;
}
elseif($lis->to_date_1 < \Carbon\Carbon::now()->format('Y-m-d'))
{
$listings->add($lis);
}
}
结果应该是:
但是,查询返回所有 3 个列表。如何修复查询以获得正确的结果?
最佳答案
我已经重新创建了你的数据库并用上面的数据测试了下面的代码。不需要使用 fooreach
然后检查这个
迁移
$table->dateTime('from_date_1');
$table->dateTime('to_date_1');
$table->dateTime('from_date_2')->nullable();
$table->dateTime('to_date_2')->nullable();
$table->dateTime('from_date_3')->nullable();
$table->dateTime('to_date_3')->nullable();
数据库
查询
$data = Listing::where(function($query){
$query->whereDate('to_date_1', '>=', Carbon::now())
->orWhereDate('to_date_2', '>=', Carbon::now())
->orWhereDate('to_date_3', '>=', Carbon::now());
})->get();
结果
[
{
"id": 1,
"from_date_1": "2021-06-10 00:00:00",
"to_date_1": "2021-08-15 00:00:00",
"from_date_2": "2021-08-16 00:00:00",
"to_date_2": "2021-08-31 00:00:00",
"from_date_3": "2021-09-01 00:00:00",
"to_date_3": "2021-09-15 00:00:00",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"from_date_1": "2021-06-25 00:00:00",
"to_date_1": "2021-08-10 00:00:00",
"from_date_2": "2021-08-11 00:00:00",
"to_date_2": "2021-08-25 00:00:00",
"from_date_3": null,
"to_date_3": null,
"created_at": null,
"updated_at": null
}
]
效率
更新
Since required answer has been amended later my answer I have updated the query as follow
$to_date_3 = Listing::whereNotNull('to_date_1')->whereNotNull('to_date_2')->whereDate('to_date_3', '<=', Carbon::now())->get();
$to_date_2 = Listing::whereNull('to_date_3')->whereNotNull('to_date_2')->whereDate('to_date_2', '<=', Carbon::now())->get();
$to_date_1 = Listing::whereNull('to_date_3')->whereNull('to_date_2')->whereDate('to_date_1', '<=', Carbon::now())->get();
$result = $to_date_1->merge($to_date_2)->merge($to_date_3);
结果
[
{
"id": 3,
"from_date_1": "2021-06-25 00:00:00",
"to_date_1": "2021-08-20 00:00:00",
"from_date_2": null,
"to_date_2": null,
"from_date_3": null,
"to_date_3": null,
"created_at": null,
"updated_at": null
}
]
效率
关于Laravel 中的 SQL 查询未返回正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68888939/