我有一个名为ad_banner_queue的表,用于根据广告权重生成队列。广告被插入到广告表中。如果所有现有的在队列中的广告都已发送给用户,则会生成队列。
现在的问题是,如果同时收到多个请求且Rand()返回相同的记录,应该如何防止发送重复的广告?
以下是代码:
<?php
/* To Get the random Ad */
public function getBanner($params) {
/* Fetch the Random from table */
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
/* In case of queue is not there generate the new queue */
if ($ads_queue === false) {
$output = $this->generateAdQueue();
//In case of something went wrong while generating the queue
if ($output == false) {
return array();
}
//Now fetch the record again
$ads_queue = (new \yii\db\Query())
->select('ad_quque_id, banner_image, unique_code')
->from('ad_banner_queue')
->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')
->where('is_sent=0')
->orderBy('RAND()')
->one();
}
/* Now, marked that one as is_sent */
Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();
return $ads_queue;
}
/**
* Below will Generate the Queue if not exist
*/
public function generateAdQueue() {
/* First check thatt there is existing queue, if so don't generate it */
$data_exist = (new \yii\db\Query())
->select('ad_quque_id')
->from('ad_banner_queue')
->where('is_sent=0')
->scalar();
if ($data_exist === false) {
/* Delete all other entries */
(new \yii\db\Query())
->createCommand()
->delete('ad_banner_queue')
->execute();
/* Fetch all banner */
$ads = (new \yii\db\Query())
->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')
->from('advertisement')
->where('status_id in (8)') //Means only fetch Approved ads
->all();
if (!empty($ads)) {
foreach ($ads as $ad) {
/* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */
$ins_fields = array();
for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {
$ins_fields[] = array($ad['ad_id']);
}
Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();
}
return true;
} else {
return false;
}
} else {
return false;
}
}