我正在使用 Laravel 和 Eloquent ORM,在为我的表开发控制器、模型和视图后,我需要提取聚合信息,但我还没有弄清楚哪种是最好的方法或最干净的“Laravel”方法。
我有一个数据库表,就像这个例子:
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');
感谢您的任何帮助或建议。
当您使用
sum()
方法时,它会执行查询并仅返回总和。您在这里想要的是获得总和和描述,因此您必须自己构建选择。这就是“Laravel”方式的样子。
控制器:
public function home()
{
$onlynew = Orderitem::onlyNew()->get();
return view('home', compact('onlynew '));
}
型号:
public function scopeOnlyNew($query)
{
return $query->where('item_status', '=', 'NEW')
->selectRaw('sum(item_qty) as qty, item_description')
->groupBy('item_description')
->orderBy('item_description');
}
请注意,查询范围的构建方式略有不同。 查询范围旨在允许您将常用的查询约束分组到单个方法中,然后将这些约束与您正在构建的任何查询重用。它们应该始终返回给定的相同查询对象,而不是像
DB::select()
这样创建一个新的查询对象。
我个人更喜欢使用 DB::table 语句。
public function scopeonlynew () {
return DB::table('order_items')->where('item_status', '=','NEW')->get();
}
让我知道这是否适合您!