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;
    }
    ```
相关推荐
CoderYanger1 小时前
Java EE 进阶:8.MyBatis 操作数据库(入门)(第二弹)
java·数据库·spring boot·spring·面试·java-ee·mybatis
CQU_JIAKE4 小时前
11.7[高体】
java·后端·spring
apcipot_rain5 小时前
C++转Java日记(04)
java·开发语言·c++
红尘散仙5 小时前
谁说终端只能敲键盘?我用 Rust 给小说阅读器加上了鼠标
前端·后端·rust
特立独行的猫A5 小时前
我给女儿写了个打字练习:一边敲键盘,一边把小学英语单词记牢
java·后端·python
陈随易6 小时前
C++26 草案被否,二十八年来头一回
前端·后端·程序员
ZhengEnCi6 小时前
Agent 工具怎么折叠海量输出才「爽」:Trae、Claude Code 的渐进式披露设计原理
前端·agent
憧憬成为java架构高手的小白7 小时前
LangGraph4j 实战(下)
java
天诰7 小时前
SA-K-11 检索会消失吗与四个未解问题
java·服务器·人工智能·python·机器学习·ai编程
IT_陈寒9 小时前
Redis内存暴涨,没想到是AOF重写捣的鬼
前端·人工智能·后端