Answer the question
In order to leave comments, you need to log in
How to use ActiveRecord in Yii2 to enter data containing a foreign key?
The database has a table galleries (ownerId (PK), object_id (FK))
Here is the model:
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
class Product extends ActiveRecord
{
public $ownerId;
public $object_id;
private $connection;
public function __construct()
{
$this->connection = Yii::$app->db;
}
public static function tableName(){
return 'galleries';
}
public static function primaryKey()
{
return 'ownerId';
}
}
public function actionProduct()
{
$model = new Product();
$model->object_id = 1;
$model->save();
return $this->render('product', ['model' => $model]);
}
INSERT INTO `galleries` (`object_id`) VALUES (1);
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`my_db.`galleries`, CONSTRAINT `galleries_ibfk_1` FOREIGN KEY (`object_id`) REFERENCES `objects` (`object_id`) ON DELETE CASCADE ON UPDATE CASCADE)
The SQL being executed was: <b>INSERT INTO `galleries` (`ownerId`) VALUES (DEFAULT)</b>
Answer the question
In order to leave comments, you need to log in
This is because you declared the attributes as properties of the class ( public $object_id;) - take that away, in Yii attributes are accessed via magic methods.
In general, personally, to connect relays, I use the ActiveRecord:: link method - a very convenient method, I advise you to pay attention to it.
I can be wrong, but you show an error not from the action given in the question.
INSERT INTO `galleries` (`ownerId`) VALUES (DEFAULT) - default is confusing.
Or you forgot to write rules() in the Product model. At least it would be safe to give an attribute, it will already be written to the database.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question