You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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,
Below is what seems to be problem
as per this commit: 4c03ea8
$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
The text was updated successfully, but these errors were encountered:
testingatswt
changed the title
MorphTo relation won't work when eager load - Solution Found!
MorphTo relation won't work when eager load if target model has different primary key
Mar 18, 2024
yahyaizhar
added a commit
to yahyaizhar/laravel-mongodb
that referenced
this issue
Mar 18, 2024
10.44.0
4.1
8.2.10
7.0.5
Description:
Follow #2669
If
morphTo()
is defined on model with$primaryKey='_id'
and target model has$primaryKey='id'
it will returnnull
when eager loadSteps to reproduce
Entities
model, having primaryKey=_id (Unmodified)and the target model if auto increamented ID, here is what is looks like
Expected behaviour
It should return the source as relation
Actual behaviour
Instead, it returns null
Proposed Solution
Below is what seems to be problem
as per this commit: 4c03ea8
$this
points to current model which is in this caseEntities::class
which is wrong since it should get the ownerKey of target model, in this caseClient
. So solution would be just pass thenull
as$ownerKey
, laravel will pick the ownerKey by it self. I already tested itThe text was updated successfully, but these errors were encountered: