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;
    }
    ```
相关推荐
黑云压城After5 分钟前
vue2实现图片自定义裁剪功能(uniapp)
java·前端·javascript
芙蓉王真的好110 分钟前
NestJS API 提示信息规范:让日志与前端提示保持一致的方法
前端·状态模式
dwedwswd16 分钟前
技术速递|从 0 到 1:用 Playwright MCP 搭配 GitHub Copilot 搭建 Web 应用调试环境
前端·github·copilot
2501_9387742930 分钟前
Leaflet 弹出窗实现:Spring Boot 传递省级旅游口号信息的前端展示逻辑
前端·spring boot·旅游
meichaoWen1 小时前
【CSS】CSS 面试知多少
前端·css
我血条子呢1 小时前
【预览PDF】前端预览pdf
前端·pdf·状态模式
90后的晨仔1 小时前
报错 找不到“node”的类型定义文件。 程序包含该文件是因为: 在 compilerOptions 中指定的类型库 "node" 的入口点 。
前端
90后的晨仔1 小时前
5分钟搭建你的第一个TypeScript项目
前端·typescript
zcl_19912 小时前
记一次ThreadLocal导致的生产事故
java
专注前端30年2 小时前
Vue2 中 v-if 与 v-show 深度对比及实战指南
开发语言·前端·vue