【问题标题】:Laravel: whereHas() with complex conditionsLaravel:whereHas() 条件复杂
【发布时间】:2018-07-28 20:05:07
【问题描述】:

假设我有两个模型,

BlockSlot,其各自的表结构为:-

blocks(id, name);
slots(id, block_id, time, status);

slots.status 的值可能为 0 表示可用或 1 表示已预订。

问题是,我只想返回那些 status 计数 1 与插槽表中的总插槽计数比率小于 0.5 的块,或者换句话说,我想返回那些插槽为50% 以上可供预订。

我有一个 laravel 雄辩的逻辑如下:-

$blocks = Block::whereHas('slots', function ($q) {
    // What might be the condition here... ?
})
->with('slots');

【问题讨论】:

  • 你是否已经对该请求进行了普通的 sql 查询?

标签: mysql sql laravel eloquent laravel-5.4


【解决方案1】:

我不确定我是否理解公式,但如果你想获得有更多可用插槽的块,你可以这样做:

$blocks = Block::withCount(['slots as booked' => function($q) {
    $q->where('status', 1);
}])
->withCount(['slots as available' => function($q) {
    $q->where('status', 0);
}])
->get();

$blocks = $blocks->filter(function ($block) {
    return $block->booked > $block->available;
});

【讨论】:

    猜你喜欢
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2017-07-27
    • 2011-02-15
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多