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

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

1. SQLSTATE23000: 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 分钟前
JAVA练习312- 二叉搜索树中第 K 小的元素
java·数据结构·算法·leetcode
淡海水9 分钟前
06-04-YooAsset源码-Unity加密解密服务
前端·unity·性能优化·c#·游戏引擎·yooasset
trigger33340 分钟前
desk-health-web-community-post
前端
倒流时光三十年41 分钟前
Logback 系列(7):常用 Appender(控制台 / 文件 / 滚动文件)
java·前端·logback
极客先躯1 小时前
高级java每日一道面试题-2026年04月18日-实战篇[Docker]-如何处理金融行业的时序数据容器化?
java·运维·docker·容器·金融·时序数据·高级面试
hdsoft_huge1 小时前
SpringBoot系列18:SpringSecurity登录鉴权,JWT无状态Token认证完整流程(生产级落地)
java·spring boot·后端
Csvn1 小时前
页面「穿越」之谜:React 中因 key 值不正确导致的渲染 Bug 排查实战
前端
浅水壁虎1 小时前
前端技术_TypeScript(第一章)
前端
野蛮人6号1 小时前
黑马天机学堂系列问题之选集8本地服务报错
java·spring cloud·黑马程序员·天机学堂·黑马天机学堂
L-影1 小时前
单体项目结构
java·开发语言