laravel-mongodb
laravel-mongodb copied to clipboard
MorphTo relation won't work when eager load if target model has different primary key
- Laravel Version:
10.44.0
- Laravel-mongodb Version:
4.1
- PHP Version:
8.2.10
- Database Driver & Version:
7.0.5
Description:
Follow #2669
If morphTo()
is defined on model with $primaryKey='_id'
and target model has $primaryKey='id'
it will return null
when eager load
Steps to reproduce
- I have model with morphTo relationship, here is
Entities
model, having primaryKey=_id (Unmodified)
class Entities extends Model
{
use HasFactory;
public function source(): MorphTo
{
return $this->morphTo(__FUNCTION__, 'source_model', 'source_id');
}
}
and the target model if auto increamented ID, here is what is looks like
class Client extends Model
{
use HasFactory, AutoIncreamentTrait;
protected $primaryKey = 'id';
}
- When calling the relation via eager load, it returns null,
Entities::with('source')->find('65f435eecd749d48b70b5c6b');
Expected behaviour
It should return the source as relation
{
"_id": "65f435eecd749d48b70b5c6b",
"source_id": 1,
"source_model": "App\\Models\\Client",
"assign_date": "2024-02-25T00:00:00.000000Z",
"unassign_date": null,
"notes": null,
"updated_at": "2024-03-15T11:50:06.217000Z",
"created_at": "2024-03-15T11:50:06.217000Z",
"status": "active",
"source": {
"_id": "65f2ec6d28c0daeb6e010c60",
"id": 1,
"name": "Anthony Rowe",
"email": "[email protected]",
"updated_at": "2024-03-15T11:50:06.217000Z",
"created_at": "2024-03-15T11:50:06.217000Z",
}
}
Actual behaviour
Instead, it returns null
{
"_id": "65f435eecd749d48b70b5c6b",
"source_id": 1,
"source_model": "App\\Models\\Client",
"assign_date": "2024-02-25T00:00:00.000000Z",
"unassign_date": null,
"notes": null,
"updated_at": "2024-03-15T11:50:06.217000Z",
"created_at": "2024-03-15T11:50:06.217000Z",
"status": "active",
"source": null
}
Proposed Solution
Below is what seems to be problem as per this commit: https://github.com/mongodb/laravel-mongodb/pull/2669/commits/4c03ea820280c8d412d7a31e6d12a794cc928408
$this
points to current model which is in this case Entities::class
which is wrong since it should get the ownerKey of target model, in this case Client
. So solution would be just pass the null
as $ownerKey
, laravel will pick the ownerKey by it self. I already tested it
Tracked in Jira PHPORM-175