
laravel查询构造器中批量处理数据集合
在laravel中,可以通过修改内置的toarray方法或自己实现一个新方法,实现类似于thinkphp中withattr功能的效果。
自定义方法
namespace app {
...
class customcollection extends collection
{
// ...其他方法
public function toarray(callable $callback = null)
{
$toarray = $this->items;
if ($callback !== null) {
$toarray = array_map($callback, $toarray);
}
// ...其他逻辑
return $toarray;
}
}
}然后在查询构造器中使用自定义方法:
立即学习“PHP免费学习笔记(深入)”;
$orders = db::table('orders')
->select('*')
->toarray(function ($order) {
$order['status'] = ['待付款', '待发货'][$order['status']];
return $order;
});修改toarray方法
另一种方法是直接修改toarray方法:
use illuminate\support\collection;
collection::macro('customtoarray', function () {
$toarray = $this->items;
foreach ($toarray as &$order) {
$order['status'] = ['待付款', '待发货'][$order['status']];
}
// ...其他逻辑
return $toarray;
});然后在查询构造器中使用:
$orders = DB::table('orders')
->select('*')
->customToArray();










