Skip to content

Removed constraint causes all rows to be loaded #55155

@BertvanHoekelen

Description

@BertvanHoekelen

Laravel Version

12.3.0

PHP Version

8.4

Database Driver & Version

MySQL

Description

The removal of the constraints in this PR causes all rows to be loaded into memory when giving a custom closure to the ofMany method.

Steps To Reproduce

public function report(?ReportType $reportType = ReportType::SOME_REPORT): HasOne
{
    return $this->hasOne(Report::class)->ofMany([], function (Builder $builder) use ($reportType) {
        $builder->where('report_type', $reportType);
    });
}

This will results in all reports with report_type x being loaded into memory as in framework version 12.1.0 it was just the rows that with the constraint.

12.1.0

Explain: Image

SELECT
	`reports`.*
FROM
	`reports`
	INNER JOIN (
		SELECT
			MAX(`reports`.`id`) AS `id_aggregate`,
			`reports`.`user_id`
		FROM
			`reports`
		WHERE
			`report_type` = ?
			AND `reports`.`user_id` = ?
			AND `reports`.`user_id` IS NOT NULL
			AND `reports`.`deleted_at` IS NULL
		GROUP BY
			`reports`.`user_id`
	) AS `reports` ON `reports`.`id_aggregate` = `reports`.`id`
	AND `reports`.`user_id` = `reports`.`user_id`
WHERE
	`reports`.`user_id` = ?
	AND `reports`.`user_id` IS NOT NULL
	AND `reports`.`deleted_at` IS NULL
LIMIT
	1

12.2.0
Explain: Image

SELECT
	`reports`.*
FROM
	`reports`
	INNER JOIN (
		SELECT
			MAX(`reports`.`id`) AS `id_aggregate`,
			`reports`.`user_id`
		FROM
			`reports`
		WHERE
			`report_type` = ?
			AND `reports`.`deleted_at` IS NULL
		GROUP BY
			`reports`.`user_id`
	) AS `reports` ON `reports`.`id_aggregate` = `reports`.`id`
	AND `reports`.`user_id` = `reports`.`user_id`
WHERE
	`reports`.`user_id` = ?
	AND `reports`.`user_id` IS NOT NULL
	AND `reports`.`deleted_at` IS NULL
LIMIT
	1

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions