Skip to content

Commit

Permalink
Merge pull request #31 from jeremyharris/issue/29
Browse files Browse the repository at this point in the history
Fix for unconventional PKs
  • Loading branch information
jeremyharris authored Nov 15, 2021
2 parents 1c0cd9e + 6184e7f commit 568b41c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
6 changes: 5 additions & 1 deletion src/ORM/LazyLoadEntityTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace JeremyHarris\LazyLoad\ORM;

use Cake\Datasource\RepositoryInterface;
use Cake\ORM\Association\BelongsTo;
use Cake\ORM\Entity;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
Expand Down Expand Up @@ -128,7 +129,10 @@ protected function _lazyLoad($property)
->associations()
->getByProperty($property);

if ($association === null || $this->get($association->getBindingKey()) === null) {
// is belongsTo and missing FK on this table? loadInto tries to load belongsTo data regardless
$isMissingBelongsToFK = $association instanceof BelongsTo && !isset($this->_fields[$association->getForeignKey()]);

if ($association === null || $isMissingBelongsToFK) {
return null;
}

Expand Down
4 changes: 2 additions & 2 deletions tests/Fixture/AuthorsFixture.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ class AuthorsFixture extends TestFixture
* @var array
*/
public $fields = [
'id' => ['type' => 'integer'],
'author_id' => ['type' => 'integer'],
'name' => ['type' => 'string', 'default' => null],
'_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
'_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['author_id']]]
];

/**
Expand Down
7 changes: 5 additions & 2 deletions tests/TestCase/ORM/LazyLoadEntityTraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public function setUp(): void

$this->connection = ConnectionManager::get('test');

$this->Authors = $this->getTableLocator()->get('Authors');
$this->Authors->setPrimaryKey('author_id');

$this->Articles = $this->getTableLocator()->get('Articles');
$this->Articles->setEntityClass(LazyLoadableEntity::class);
$this->Articles->belongsTo('Authors');
Expand Down Expand Up @@ -313,7 +316,7 @@ public function testGetLazyLoadsOnce()

$author = $comment->author;

$this->assertEquals(2, $author->id);
$this->assertEquals(2, $author->author_id);

// ensure it is grabbed from _properties and not lazy loaded again (which calls repository())
$comment->author;
Expand Down Expand Up @@ -375,7 +378,7 @@ public function testEmptySource()
$comment = new Comment(['id' => 1, 'user_id' => 2]);
$author = $comment->author;

$this->assertEquals(2, $author->id);
$this->assertEquals(2, $author->author_id);
}

/**
Expand Down

0 comments on commit 568b41c

Please sign in to comment.