请教,Laravel中查询构造器如何批量处理数据集合

类似于 think-orm 的 withAttr 功能。

如 我查询出了一组订单数据, 需要把其中的 status 字段变成可读的字符串形式, 0:待付款 1待发货

think-orm 中的查询构造器可以这样实现:

$orders = 
    Db::table('orders')
    -> withAttr([
        'status' => function($status) {
            return ['待付款', '待发货'][$status];
        }
    ])
    -> page(1, 15)
    -> select();

return $orders -> toArray();

Laravel 中的查询构造器有类似的功能吗 还是说 只能取出数据后再循环一遍处理

foreach ($orders as &$order) {
    $order['status'] = ['待付款', '待发货'][$order['status']];
}

return $orders;
阅读 2.6k
2 个回答

自己实现或修改内置的toArray方法。

<?php


namespace App\Services;

use Illuminate\Support\Collection;


class CollectionAttributesProcess
{
    /**
     * Default created_at and updated_at time types.
     */
    const DEFAULT_TIME_TYPE = 'Y/m/d H:i:s';

    /**
     * Default fields name.
     */
    const DEFAULT_CREATED_AT_FIELD = 'created_at';
    const DEFAULT_UPDATED_AT_FIELD = 'updated_at';

    /**
     * Array children attributes changing
     * @param Collection $collection
     * @param array $attributes
     * @param bool $auto_times
     * @return array|Collection
     */
    static public function make(Collection $collection, array $attributes = [], $auto_times = true) {
        $collection = $collection -> toArray();
        foreach ($collection as &$data){
            $data = json_decode(json_encode($data), true);
            foreach ($auto_times ? self::time_default_values($attributes) : $attributes as $field => $func)
                $data[$field] = $func($data[$field] ?? null, $data);
        }

        return $collection;
    }

    /**
     * Time defaults values checking.
     * @param array $attributes
     * @return array
     */
    static private function time_default_values(array $attributes) {
        foreach ([self::DEFAULT_CREATED_AT_FIELD, self::DEFAULT_UPDATED_AT_FIELD] as $_type) {
            ($attributes[$_type] ?? null) || $attributes[$_type] = self::$_type();
        }

        return $attributes;
    }

    /**
     * Default created_at field time return.
     * @return \Closure
     */
    static private function created_at() {
        return
            function($created_at) {
                return date(self::DEFAULT_TIME_TYPE, $created_at);
            };
    }

    /**
     * Default updated_at field time return.
     * @return \Closure
     */
    static private function updated_at() {return self::created_at();}

}

查询构建器的话就只有自己去实现了。

使用模型的话可以用
Laravel 模型的 属性修改器 中的自定义转换器可以实现这样的效果,或者定义访问器也可以。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题