Skip to content

Commit

Permalink
Merge pull request #10074 from cakephp/issue-10054
Browse files Browse the repository at this point in the history
Improve error message on belongsToMany associations
  • Loading branch information
lorenzo committed Jan 21, 2017
2 parents ecf2d2b + fb1f947 commit 783cfd1
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 783cfd1

Please sign in to comment.