laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

MorphTo relation won't work when eager load if target model has different primary key

Open testingatswt opened this issue 3 months ago • 1 comments

  • 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
{
    use HasFactory, AutoIncreamentTrait;

	protected $primaryKey = 'id';
}
  1. 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

image

$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

testingatswt avatar Mar 18 '24 11:03 testingatswt

Tracked in Jira PHPORM-175

GromNaN avatar Apr 26 '24 10:04 GromNaN