-
Type: Improvement
-
Resolution: Fixed
-
Priority: Unknown
-
Affects Version/s: None
-
Component/s: Laravel
-
Not Needed
-
testingatswt has created Issue #2783: MorphTo relation won't work when eager load if target model has different primary key in laravel-mongodb. This Jira ticket was filed by GromNaN
Issue Text:
- 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
1. 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
```
2. 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":
}
```
Actual behaviour
Instead, it returns null
```
```
Proposed Solution
Below is what seems to be problem
as per this commit: https://github.com/mongodb/laravel-mongodb/pull/2669/commits/4c03ea820280c8d412d7a31e6d12a794cc928408
![image](https://github.com/mongodb/laravel-mongodb/assets/30407057/c9d7b239-f450-4fe3-9a6f-2cee45e5c6f1)
`$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