A
A
AlexAll2020-05-07 21:03:14
Yii
AlexAll, 2020-05-07 21:03:14

How to build an upsert request with an array in yii2?

Hello, there is an array $news_id with news ads,
there is a SQL query

Yii::$app->db->createCommand()
        ->upsert(
            'display',
            [
                'hash' => md5($news_id . strtotime($date)),
                'date' => strtotime($date),
                'sum' => 1,
                'news_id' => $news_id ,
            ], [
                'sum' => new \yii\db\Expression('sum + 1'),
            ]
        )
        ->execute();


How can I make this request add or update the counter for several news at once, or can it be done with only a few requests, depending on the number of $news_id ?
This hash is from gluing the news id and the date so that the counter is counted by date
'hash' => md5($news_id . strtotime($date)),

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2020-05-07
@AlexAll

You need to do something like this, form an sql query in the required format (updated):

$m = new Migration();
        $start = "INSERT INTO `display` (`hash`, `date`,`sum`, `news_id`) ";
        $insert_data = [];
        // $news_id = [здесь ваши ид];
        // $date = ""; здесь дата

        foreach ($news_id  as $id)
        {
            $time = strtotime($date);
            $hash =  md5($id . $time);
            $insert_data[] = " ('$hash', $time, 1, $id)";
        }

        $m->execute("$start VALUES " . implode(", ",$insert_data) . " ON DUPLICATE KEY UPDATE `sum` = `sum` + 1;");

I
Ivan Ivanov, 2020-05-07
@maksim_fix

Iterate through the array with the news, for each news you make your own request, why do you need everything at once?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question