yiisoft/yii2 · error · yii\base\InvalidCallException
Unable to link models: the models being linked cannot be new
Error message
Unable to link models: the models being linked cannot be newly created.
What it means
Error "Unable to link models: the models being linked cannot be newly created." thrown in yiisoft/yii2.
Source
Thrown at framework/db/BaseActiveRecord.php:1318
* junction table which contains the primary key values from both models.
*
* Note that this method requires that the primary key value is not null.
*
* @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
* @param ActiveRecordInterface $model the model to be linked with the current one.
* @param array $extraColumns additional column values to be saved into the junction table.
* This parameter is only meaningful for a relationship involving a junction table
* (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
* @throws InvalidCallException if the method is unable to link two models.
*/
public function link($name, $model, $extraColumns = [])
{
/** @var ActiveQueryInterface|ActiveQuery $relation */
$relation = $this->getRelation($name);
if ($relation->via !== null) {
if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
}
if (is_array($relation->via)) {
/** @var ActiveQuery $viaRelation */
list($viaName, $viaRelation) = $relation->via;
$viaClass = $viaRelation->modelClass;
// unset $viaName so that it can be reloaded to reflect the change
unset($this->_related[$viaName]);
} else {
$viaRelation = $relation->via;
$viaTable = reset($relation->via->from);
}
$columns = [];
foreach ($viaRelation->link as $a => $b) {
$columns[$a] = $this->$b;
}
foreach ($relation->link as $a => $b) {
$columns[$b] = $model->$a;
}View on GitHub (pinned to 66f00d18a2)
When it happens
Trigger: Thrown at framework/db/BaseActiveRecord.php:1318 when the library encounters an invalid state.
Common situations: See trigger scenarios.
AI-assisted analysis of yiisoft/yii2@66f00d18a2 (2026-08-17).
Data as JSON: /api/errors/28da343ae485dd35.
Report an issue: GitHub.