
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();以上就是Laravel 查询构造器如何实现批量处理数据集合类似 ThinkPHP 中 withAttr 功能的效果?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号