mysql - 基于关系中最新模型的列和父模型的列过滤范围

标签 mysql database relationship laravel-5

我有两个表:auctionsbids。在拍卖中,我有一个start_amount字段,在bids中,有一个amount字段。这两个表还具有 created_atmodified_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/

相关文章:

ruby-on-rails - 单表继承(Rai​​ls)的一对多关系问题

mysql - 用户中的参数错误#index

mysql - cakephp查找最近24小时的记录

php - pdo_mysql 在 centos 6.7 上不可用

php - 有什么原因导致我的 php 脚本中的查询不起作用吗?

php - Zend 框架关系与表选择

MySQL - 父+子类别总数

c# - 同时针对云和自托管应用程序?

javascript - 如何将 JavaScript 中的对象关联或关联到 HTML 元素?

mysql - 我想在 MySQL 中做的事情