S
S
skajtersen2017-05-25 10:48:12
Yii
skajtersen, 2017-05-25 10:48:12

How to insert values ​​into a table by foreign key of another table?

There are two tables

Logs  (log_id (PK), query_type (FK from query_type_id)
QueryTypes (query_type_id (PK), query_type (UNIQUE))

There is a loop for inserting data, inside which is executed
$types = new QueryTypes();
 $types->query_type = нужные данные;
 $types->save();

 $logs = new Logs();
 $logs->query_type = $types->query_type_id;
 $logs->save();

Due to the unique value, the query_typeinsertion into the log table is performed once, after the unique value is encountered for the first time. Tell me how to get the value query_type_idto insert into the table with logs.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2017-05-25
@skajtersen

If I understood your problem correctly, then in the simplest version, like this:

$types = find()->where(['query_type' => 'нужные данные'])->one();
if (is_null($types)) {
    $types = new QueryTypes();
    $types->query_type = 'нужные данные';
    $types->save();
}

M
maximw, 2017-05-25
@maximw

I know how to do it in pure SQL (with PDO or MySQLi), but I don't know how with your ORM.
It would be something like this:

$mysqli->query('INSERT INTO `QueryTypes` SET `query_type` = "нужные данные" ON DUPLICATE KEY UPDATE `id` = LAST_INSERT_ID(`id`)'); 
//echo $mysqli->insert_id; тут будет ID новой записи или той которая была обновлена по уникальному ключу

 $logs = new Logs();
 $logs->query_type = $mysqli->insert_id;
 $logs->save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question