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;
    }
    ```
相关推荐
土司大王22 分钟前
LeetCode hot100——34.在排序数组中查找元素的第一个和最后一个位置:Java 二分模板、边界分析
java·算法·leetcode
金金计较.36 分钟前
Go语言-3
java·开发语言·golang
Wang's Blog1 小时前
Java框架快速入门: Spring Security+OAuth2之元注解简化权限表达式
java·数据库·spring
xifangge20252 小时前
AGENTS.md 怎么写?涵盖 Java、Python、Vue、Go 的 8 套开箱即用模板
java·vue.js·python
几何心凉2 小时前
没有万能模型:我用 AiiOnly Token Plan,把多款大模型的长处拼进同一个项目
前端
Wang's Blog2 小时前
Java框架快速入门: Spring Security+OAuth2之云服务集成与多因子认证设计
java·开发语言·spring
kyriewen2 小时前
Claude Code 的额度今天缩水了17%——官方公告上写的是"永久提高25%"
前端·ai编程·claude
liangsheng_g3 小时前
SpringAOP拦截器链递归与事务钩子补偿源码实战
java·spring
雪芽蓝域zzs3 小时前
vue解构平铺VS对象包裹
前端·javascript·vue.js
SL_staff3 小时前
制造业私有化文档平台的技术实践:从知识孤岛到可追溯知识资产
java·spring·开源