Skip to content

Commit d339c79

Browse files
committed
Exclude primary key columns when creating belongsto
Merge branch 'issue-394' into master.
2 parents 1e9f063 + fa49e71 commit d339c79

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

src/Shell/Task/ModelTask.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -323,7 +323,7 @@ public function findBelongsTo($model, array $associations)
323323
{
324324
$schema = $model->getSchema();
325325
foreach ($schema->columns() as $fieldName) {
326-
if (!preg_match('/^.+_id$/', $fieldName)) {
326+
if (!preg_match('/^.+_id$/', $fieldName) || ([$fieldName] === $schema->primaryKey())) {
327327
continue;
328328
}
329329

tests/TestCase/Shell/Task/ModelTaskTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,25 @@ public function testBelongsToGenerationIdMidColumn()
512512
$this->assertEquals([], $result);
513513
}
514514

515+
/**
516+
* Test that belongsTo generation ignores primary key fields
517+
*
518+
* @return void
519+
*/
520+
public function testBelongsToGenerationPrimaryKey()
521+
{
522+
$model = TableRegistry::get('Articles');
523+
$model->schema([
524+
'usr_id' => ['type' => 'integer'],
525+
'name' => ['type' => 'string'],
526+
'_constraints' => [
527+
'primary' => ['type' => 'primary', 'columns' => ['usr_id']]
528+
]
529+
]);
530+
$result = $this->Task->findBelongsTo($model, []);
531+
$this->assertEquals([], $result);
532+
}
533+
515534
/**
516535
* test that hasOne and/or hasMany relations are generated properly.
517536
*

0 commit comments

Comments
 (0)