Skip to content
This repository has been archived by the owner on Dec 11, 2020. It is now read-only.

Commit

Permalink
Merge pull request #483 from jadb/fix-assoc-entities-dep
Browse files Browse the repository at this point in the history
Fix cases where no entities prev. inserted
  • Loading branch information
fzaninotto committed Mar 18, 2015
2 parents 5ae6a7c + 7725414 commit 3e075bb
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/Faker/ORM/CakePHP/EntityPopulator.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,24 @@ public function guessModifiers($populator)
$modifiers['belongsTo' . $assoc->name()] = function ($data, $insertedEntities) use ($assoc) {
$table = $assoc->target();
$foreignModel = $table->alias();
$foreignKey = $insertedEntities[$foreignModel][array_rand($insertedEntities[$foreignModel])];

$foreignKeys = [];
if (!empty($insertedEntities[$foreignModel])) {
$foreignKeys = $insertedEntities[$foreignModel];
} else {
$foreignKeys = $table->find('all')
->select(['id'])
->map(function ($row) {
return $row->id;
})
->toArray();
}

if (empty($foreignKeys)) {
throw new \Exception(sprintf('%s belongsTo %s, which seems empty at this point.', $this->getTable($this->class)->table(), $assoc->table()));
}

$foreignKey = $foreignKeys[array_rand($foreignKeys)];
$primaryKey = $table->primaryKey();
$data[$assoc->foreignKey()] = $foreignKey;
return $data;
Expand Down

0 comments on commit 3e075bb

Please sign in to comment.