2015-06-08 31 views
3

我正在从数据库收集一些数据,然后将其显示在索引视图中。在那里我有每一行附近的复选框,所以我可以让用户选择他们的最爱。如何使用Yii2更新/向数据库插入值数组(许多值为重复的一个ID)

enter image description here

图片和文本从一个表选择cpv。该表具有字段:id,title,image。由于登录用户可以选择最多3个条目作为收藏夹,因此我使用表来存储用户和他选择的cpv.id之间的关系。 user_cpv表具有列:id,user_id,cpv_id

我做了一些显示数据+复选框的肮脏方式,并且我将某些方法传递给应该保存cpv.id的actionUpdate的信息(cpv.id)。但我无法弄清楚如何将所有这些保存到user_cpv表中。有人可以给我一些关于如何正确执行此操作的想法,以及如何验证用户无法选择超过3个盒子?这里是我的代码:

索引视图:

<?php foreach ($values as $data): ?> 
    <tr> 
     <td>Img goes here</td> 
     <td>Title goes here</td> 

     <?php // here I have some dirty code, for each row displayed I am executing query that should find entry in 
       // user_cpv table where cpv_id there is == with the cpv.id taken drom cpv table. 
       // can this be done more efficient ? 
     ?> 

     <?php $cpv = UserCpv::getCpvByCpvId($data['cpvId']) ?> 
     <?php if ($cpv): ?> 
      <td><?= Html::checkbox('favorite[]', true, ['value' => $data['cpvId']]) ?></td> 
     <?php else: ?> 
      <td><?= Html::checkbox('favorite[]', false, ['value' => $data['cpvId']]) ?></td> 
     <?php endif ?> 

    </tr> 
<?php endforeach ?> 

表单打开与HTML ::形式:

我actionUpdate:

public function actionUpdate() 
{ 
    $userId = Yii::$app->user->identity->id; 

    // array of checked cpv.ids (['0' => someId, ['1' => otherCheckedId]]) 
    $favorites = Yii::$app->request->post('favorite'); 

    $model = UserCpv::findOne(['user_id' => $userId]); 

    if ($model) 
    { 
     // this does not work 
     $update = UserCpv::updateAll(['cpv_id' => $favorites], "user_id = $userId"); 

     return $this->render('index', [ 
      'model' => $model 
     ]); 
    } 
    else 
    { 
     # code... 
    } 
    // ??? 
} 

做任何人有任何想法如何这应该做得适当吗?

回答

2

我看到两种方法:第一种是创建'batchUpdate'方法 - 但对于不同的数据库类型它不会相同。所以我会描述第二个,因为它看起来很简单。

1. Remove all user relations: 

    UserCpv::deleteAll(['user_id' => $userId]); 

2. Create array for batchInsert method: 

    $data = []; 
    foreach($favorites as $cpv_id) { 
     $data[] = ['cpv_id' => $cpv_id, 'user_id' => $userId]; 
    } 

3. Batch insert your data 

    Yii::$app->db->createCommand()->batchInsert(
     UserCpv::tableName(), 
     ['cpv_id', 'user_id'], 
     $data 
    )->execute(); 
+0

因此,我在删除一个用户的数据之前,我做了batchInsert?有趣。你认为这是考虑表演的有效方法吗?系统中可能有大约10至20K个用户。 – offline

+0

问题是你需要检查所有的用户关系并删除它们,如果它们从$ favorites数组中缺失 - 所以我认为你不会找到更快的方法。而且这个速度非常快,因为它只需要两个数据库请求。 –

+0

这是工作,谢谢! – offline

相关问题