Laravel 5.3 Eloquent连接具有多个条件连接的表

时间:2017-10-31 07:47:42

标签: php laravel join eloquent having-clause

我对使用有计数的左连接表有疑问,选择要用下述条件显示的主表:

select  b.id, b.location_name, b.box_identity
from    box b
    left join device d on b.id = d.box_id
                      and d.deleted_at is null
group by b.id, b.location_name, b.box_identity
having count(d.*) < COALESCE(b.device_slot, 3)
order by b.id desc

我尝试使用这样的雄辩代码,但DB :: raw无法在$ join函数中使用

$boxes = Box::leftJoin('device', function($join) {
    $join->on('box.id', '=', 'device.box_id');
    $join->on(DB::raw('device.deleted_at is null'));
})
->select('box.id', 'box.box_identity', 'box.location_name')
->groupBy('box.id', 'box.box_identity', 'box.location_name')
->havingRaw('COUNT(device.*) < COALESCE(box.device_slot, 3)')
->orderBy('box.id', 'desc')
->get();

如何使用laravel eloquent实现此查询?提前谢谢!

1 个答案:

答案 0 :(得分:2)

使用它:

import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, ListedColormap, BoundaryNorm
import matplotlib.cm as cm
from numpy import arange

fig, ax = plt.subplots()

my_cm = ListedColormap(['#a71b1b','#94258f','#ea99e6','#ec9510','#ece43b','#a3f8ff','#2586df','#035e0d'])
bounds=range(8)
norm = BoundaryNorm(bounds, my_cm.N)
mappable = cm.ScalarMappable(cmap=my_cm)
mappable.set_array(bounds)

data = [] # also x and y can be []
ax.scatter(x=range(my_cm.N), y=[1]*my_cm.N, c=data, edgecolors='face', cmap=my_cm, s=50)
cbar = fig.colorbar(mappable, ax=ax, boundaries=arange(-0.5,8,1), ticks=bounds, norm=norm)
cbar.ax.tick_params(axis='both', which='both',length=0)