laravel chunkById 分块查询 使用时的问题

laravel chunkById 分块查询 使用时容易出现的问题

1. SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous

使用chunkById时,单表进行分块查询,是不会出现id重复的,当用两个表进行 join 查询,如果两个表都存在ID,则会报以上的错误信息

php 复制代码
DB::table('table1')
	->select(['table1.id'])
    ->join('table2', 'table1.id', '=', 'table2.id')
    ->orderBy('table1.id')
    ->chunkById(100, function ($results) {
     
    });

如何解决 :需要指定第三个参数是用哪个表的ID,例如 table1.id

需要指定第四个参数,参数形参为 $alias,

复制代码
 $lastId = $results->last()->{$alias};

意为查询出数据以后获取对应的属性,来查询最大值,相当于只要在查询的字段中取值即可, 例如 id

如果不指定第四个参数:会报 Undefined property: stdClass::$table1.id

复制代码
 $alias = $alias ?: $column;

第一页执行完成以后,来查询最大的ID, $alias = table1.id

复制代码
$results->last()->table1.id

查询出的值内并不会有 table1.id 的key

以下为源码:

php 复制代码
    /**
     * Chunk the results of a query by comparing numeric IDs.
     *
     * @param  int  $count
     * @param  callable  $callback
     * @param  string  $column
     * @param  string  $alias
     * @return bool
     */
    public function chunkById($count, callable $callback, $column = 'id', $alias = null)
    {
        $alias = $alias ?: $column;

        $lastId = 0;

        do {
            $clone = clone $this;

            // We'll execute the query for the given page and get the results. If there are
            // no results we can just break and return from here. When there are results
            // we will call the callback with the current chunk of these results here.
            $results = $clone->forPageAfterId($count, $lastId, $column)->get();

            $countResults = $results->count();

            if ($countResults == 0) {
                break;
            }

            // On each chunk result set, we will pass them to the callback and then let the
            // developer take care of everything within the callback, which allows us to
            // keep the memory low for spinning through large result sets for working.
            if ($callback($results) === false) {
                return false;
            }

            $lastId = $results->last()->{$alias};

            unset($results);
        } while ($countResults == $count);

        return true;
    }
    ```
相关推荐
乌夷3 分钟前
axios结合AbortController取消文件上传
开发语言·前端·javascript
晓晓莺歌27 分钟前
图片的require问题
前端
唐僧洗头爱飘柔952734 分钟前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
骑牛小道士1 小时前
Java基础 集合框架 Collection接口和抽象类AbstractCollection
java
码农黛兮_461 小时前
CSS3 基础知识、原理及与CSS的区别
前端·css·css3
alden_ygq1 小时前
当java进程内存使用超过jvm设置大小会发生什么?
java·开发语言·jvm
水银嘻嘻1 小时前
web 自动化之 Unittest 四大组件
运维·前端·自动化
(((φ(◎ロ◎;)φ)))牵丝戏安1 小时前
根据输入的数据渲染柱形图
前端·css·css3·js
triticale1 小时前
【Java】网络编程(Socket)
java·网络·socket
淘源码d1 小时前
什么是ERP?ERP有哪些功能?小微企业ERP系统源码,SpringBoot+Vue+ElementUI+UniAPP
java·源码·erp·erp源码·企业资源计划·企业erp·工厂erp