B
B
Bohdan_Vasilchuk2016-03-29 14:14:39
Yii
Bohdan_Vasilchuk, 2016-03-29 14:14:39

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';
    } 
}

This is how I enter data in the controller (in this example, for the test, they are constant):
public function actionProduct()
    {
        $model = new Product();
        $model->object_id = 1;
        $model->save();
        return $this->render('product', ['model' => $model]);
    }

Thus, I expect that the following query will be executed : That is, we do not specify the ownerId due to the fact that the auto-increment, but we set the value for the object_id. At the same time, in the table to which this key refers, the value 1 already exists at the time the query is executed. What do I get:
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>

Questions:
1) Why is such a request trying to be executed?
2) How do you enter this information? Is it really necessary to make another model for the table to which we refer and write links for them in the code of the current model?
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mitaichik, 2016-03-29
@mitaichik

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.

N
Nikita, 2016-03-29
@bitver

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 question

Ask a Question

731 491 924 answers to any question