Skip to content

Commit 568b41c

Browse files
authored
Merge pull request jeremyharris#31 from jeremyharris/issue/29
Fix for unconventional PKs
2 parents 1c0cd9e + 6184e7f commit 568b41c

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

src/ORM/LazyLoadEntityTrait.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
namespace JeremyHarris\LazyLoad\ORM;
33

44
use Cake\Datasource\RepositoryInterface;
5+
use Cake\ORM\Association\BelongsTo;
56
use Cake\ORM\Entity;
67
use Cake\ORM\Table;
78
use Cake\ORM\TableRegistry;
@@ -128,7 +129,10 @@ protected function _lazyLoad($property)
128129
->associations()
129130
->getByProperty($property);
130131

131-
if ($association === null || $this->get($association->getBindingKey()) === null) {
132+
// is belongsTo and missing FK on this table? loadInto tries to load belongsTo data regardless
133+
$isMissingBelongsToFK = $association instanceof BelongsTo && !isset($this->_fields[$association->getForeignKey()]);
134+
135+
if ($association === null || $isMissingBelongsToFK) {
132136
return null;
133137
}
134138

tests/Fixture/AuthorsFixture.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ class AuthorsFixture extends TestFixture
2929
* @var array
3030
*/
3131
public $fields = [
32-
'id' => ['type' => 'integer'],
32+
'author_id' => ['type' => 'integer'],
3333
'name' => ['type' => 'string', 'default' => null],
34-
'_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['id']]]
34+
'_constraints' => ['primary' => ['type' => 'primary', 'columns' => ['author_id']]]
3535
];
3636

3737
/**

tests/TestCase/ORM/LazyLoadEntityTraitTest.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ public function setUp(): void
4646

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

49+
$this->Authors = $this->getTableLocator()->get('Authors');
50+
$this->Authors->setPrimaryKey('author_id');
51+
4952
$this->Articles = $this->getTableLocator()->get('Articles');
5053
$this->Articles->setEntityClass(LazyLoadableEntity::class);
5154
$this->Articles->belongsTo('Authors');
@@ -313,7 +316,7 @@ public function testGetLazyLoadsOnce()
313316

314317
$author = $comment->author;
315318

316-
$this->assertEquals(2, $author->id);
319+
$this->assertEquals(2, $author->author_id);
317320

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

378-
$this->assertEquals(2, $author->id);
381+
$this->assertEquals(2, $author->author_id);
379382
}
380383

381384
/**

0 commit comments

Comments
 (0)