我有两个表:auctions
和 bids
。在拍卖
中,我有一个start_amount
字段,在bids
中,有一个amount
字段。这两个表还具有 created_at
和 modified_at
时间戳列。我希望能够检索与特定范围内的最高出价(或最新出价,无论您如何查看)相匹配的拍卖列表。
过去一周我一直在研究这个问题,但只能根据所有出价进行过滤,而不是根据最新(或最低)出价(包括start_amount
.) 我如何实现我想要的目标?
我尝试过的代码:
if (request()->has('bid_range'))
$auctions->with(['bids' => function ($query) use ($bid_min, $bid_max) {
$query->whereBetween('amount', [$bid_min, $bid_max])->orWhereBetween('start_amount', [$bid_min, $bid_max])->orderBy('created_at', 'desc')->get();
}]);
最佳答案
如果我错了,请纠正我,但您可能正在尝试这样做:
select *
from auctions
where exists
(select 1
from bids
where amount > 10 and amount < 20
and bids.auctions_id = auction.id)
所以,Laravel 的方式:
DB::table('auctions')
->whereExists(function ($query) use ($bid_min, $bid_max) {
$query->from('bids')
->whereRaw("'amount' > $bid_min and 'amount' < $bid_max")
->whereRaw('bids.auctions_id = auction.id');
})
->get();
这就是你想要的吗?
关于mysql - 基于关系中最新模型的列和父模型的列过滤范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37030088/