Skip to content

Commit

Permalink
Improve error message on belongsToMany associations
Browse files Browse the repository at this point in the history
Name the correct table when bindingKey() is empty.

Refs #10054
  • Loading branch information
markstory committed Jan 21, 2017
1 parent ecf2d2b commit fb1f947
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/ORM/Association.php
Expand Up @@ -900,8 +900,9 @@ protected function _joinCondition($options)

if (count($foreignKey) !== count($bindingKey)) {
if (empty($bindingKey)) {
$msg = 'The "%s" table does not define a primary key. Please set one.';
throw new RuntimeException(sprintf($msg, $this->target()->table()));
$table = $this->isOwningSide($this->source()) ? $this->source()->table() : $this->target()->table();
$msg = 'The "%s" table does not define a primary key, and cannot have join conditions generated.';
throw new RuntimeException(sprintf($msg, $table));
}

$msg = 'Cannot match provided foreignKey for "%s", got "(%s)" but expected foreign key for "(%s)"';
Expand Down
17 changes: 17 additions & 0 deletions tests/TestCase/ORM/Association/BelongsToManyTest.php
Expand Up @@ -1038,6 +1038,23 @@ public function testGeneratedAssociations()
$this->assertEquals('target_foreign_key', $jointAssoc->foreignKey());
}

/**
* Tests that eager loading requires association keys
*
* @expectedException RuntimeException
* @expectedExceptionMessage The "tags" table does not define a primary key
* @return void
*/
public function testEagerLoadingRequiresPrimaryKey()
{
$table = TableRegistry::get('Articles');
$tags = TableRegistry::get('Tags');
$tags->schema()->dropConstraint('primary');

$table->belongsToMany('Tags');
$table->find()->contain('Tags')->first();
}

/**
* Tests that fetching belongsToMany association will not force
* all fields being returned, but intead will honor the select() clause
Expand Down

0 comments on commit fb1f947

Please sign in to comment.