core
core copied to clipboard
[Laravel] LinksHandler does not properly handle a `MorphOneOrMany` relationship
API Platform version(s) affected: 4.1.15
Description
When trying to get a collection of related models via a polymorphic relationship, the query is not scoped to model parent class.
Structure:
Model 1: Project Property: attachments(): MorphMany
Model 2: Attachment
How to reproduce
Create an operation for the nested resource:
new GetCollection(
uriTemplate: '/projects/{id}/attachments',
uriVariables: [
'id' => new Link(
fromProperty: 'attachments',
fromClass: Project::class,
),
],
),
Dump the query:
select * from `attachments` where `attachments`.`model_id` = ?
This query will return all Attachments with the provided model ID, even if the model_type is incorrect.
A properly scoped Morph relationship should output the following to account for other model classes with the same model ID:
select * from `attachments` where `attachments`.`model_type` = ? and `attachments`.`model_id` = ? and `attachments`.`model_id` is not null
This is the output of: $project->attachments()->toSql()
Possible Solution
Add the following to LinksHandler on L111:
if ($relationQuery instanceof MorphOneOrMany) {
return $builder
->where($relationQuery->getForeignKeyName(), $identifier)
->where($relationQuery->getMorphType(), $relationQuery->getMorphClass());
}