【发布时间】:2017-07-31 23:52:09
【问题描述】:
我正在使用 Laravel 和 Eloquent ORM,在为我的表开发控制器、模型和视图之后,我需要提取聚合信息,但我不知道这是最好的方法还是最干净的“Laravel”方法.
我有一个 db table 像这个例子:
Schema::create('order_items', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('order_id')->unsigned();
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->string('item_description');
$table->integer('item_qty');
$table->status('item_status');
});
详细数据可以是:
2 2017-02-28 12:48:07 2017-02-28 12:48:31 1 ProductB 2 NEW
4 2017-02-28 12:48:17 2017-02-28 12:48:17 1 ProductC 3 NEW
29 2017-03-10 10:49:47 2017-03-10 10:49:47 1 ProductC 23 CLOSED
40 2017-03-10 10:49:47 2017-03-10 10:49:47 1 ProductB 2 SHIPPED
1 2017-02-28 11:04:28 2017-02-28 11:29:10 3 ProductA 1 NEW
28 2017-03-10 10:49:47 2017-03-10 10:49:47 3 ProductB 22 CLOSED
39 2017-03-10 10:49:47 2017-03-10 10:49:47 3 ProductA 1 SHIPPED
5 2017-02-28 14:36:54 2017-02-28 14:36:54 6 ProductD 4 NEW
6 2017-02-28 14:37:01 2017-02-28 14:37:01 6 ProductD 5 NEW
30 2017-03-10 10:49:47 2017-03-10 10:49:47 6 ProductD 24 CLOSED
41 2017-03-10 10:49:47 2017-03-10 10:49:47 6 ProductC 3 SHIPPED
在控制器中我使用范围
public function home()
{
$onlynew = Orderitem::onlynew ();
return view('home', compact('onlynew '));
}
模型是
public function scopeonlynew ($query) {
return \DB::select('SELECT item_description, sum(item_qty) qty
FROM order_items
WHERE item_status = ?
GROUP BY item_description',['NEW']);
}
在视图中我可以通过这种方式访问数据
<div class="row">
<ul>
@foreach ($onlynew as $newitem)
<li>{{$newitem->item_description}} - {{$newitem->qty}}</li>
@endforeach
</ul>
</div>
是否可以使用类似于以下示例的语法或框架不允许使用构建器的此类查询?
return $query->where('item_status', '=', 'NEW')
->sum('item_qty')
->groupBy('item_description')
->orderBy('item_description');
感谢您的任何帮助或建议。
【问题讨论】: