Skip to content
6 changes: 5 additions & 1 deletion src/Relations/MorphTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@ public function addConstraints()
// For belongs to relationships, which are essentially the inverse of has one
// or has many relationships, we need to actually query on the primary key
// of the related models matching on the foreign key that's on a parent.
$this->query->where($this->ownerKey, '=', $this->parent->{$this->foreignKey});
$this->query->where(
$this->ownerKey ?: $this->query->getModel()->getKeyName(),
'=',
$this->parent->{$this->foreignKey},
);
}
}

Expand Down
5 changes: 5 additions & 0 deletions tests/Models/Photo.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ public function hasImage(): MorphTo
{
return $this->morphTo();
}

public function hasImageWithCustomOwnerKey(): MorphTo
{
return $this->morphTo(ownerKey: 'cclient_id');
}
}
19 changes: 19 additions & 0 deletions tests/RelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,25 @@ public function testMorph(): void
$relations = $photos[1]->getRelations();
$this->assertArrayHasKey('hasImage', $relations);
$this->assertInstanceOf(Client::class, $photos[1]->hasImage);

// inverse
$photo = Photo::query()->create(['url' => 'https://graph.facebook.com/hans.thomas/picture']);
$client = Client::create(['name' => 'Hans Thomas']);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@hans-thomas: Was there a particular reason you used Photo::query()->create() above but Client::create() here? Best I could tell, they resolve to the same Builder::create() method.

Client::create() just ends up forwarding the call through Model::__call().

$photo->hasImage()->associate($client)->save();

$this->assertCount(1, $photo->hasImage()->get());
$this->assertInstanceOf(Client::class, $photo->hasImage);
$this->assertEquals($client->_id, $photo->hasImage->_id);

// inverse with custom ownerKey
$photo = Photo::query()->create(['url' => 'https://graph.facebook.com/young.gerald/picture']);
$client = Client::create(['cclient_id' => (string) (new ObjectId()), 'name' => 'Young Gerald']);
$photo->hasImageWithCustomOwnerKey()->associate($client)->save();

$this->assertCount(1, $photo->hasImageWithCustomOwnerKey()->get());
$this->assertInstanceOf(Client::class, $photo->hasImageWithCustomOwnerKey);
$this->assertEquals($client->cclient_id, $photo->has_image_with_custom_owner_key_id);
$this->assertEquals($client->_id, $photo->hasImageWithCustomOwnerKey->_id);
}

public function testHasManyHas(): void
Expand Down