我是yii的新手,我无法将多个选定的数据存储到数据库。有三个表在我的数据库'产品' '卖家'和'productseller'与多对多的关系。Product表包含pro_name和pro_id字段,seller表包含sel_id和sel_name字段,productseller表包含pro_id和sel_id字段。我所做的是从下拉列表中选择卖家名称和相关的多个产品,然后将它们存储在productseller表中。
我的观点:
<div class="row">
<?php echo $form->labelEx($model,'Select Seller'); ?>
<?php echo $form->dropDownList($model,'sel_id',
CHtml::listData(Seller::model()->findAll(), 'sel_id', 'sel_name')); ?>
<?php echo $form->error($model,'sel_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'Choose Products'); ?>
<?php //echo $form->textField($model,'maincat_id'); ?>
<?php echo $form->dropDownList($model, 'pro_id',
CHtml::listData(Product::model()->findAll(), 'pro_id', 'pro_name'),
array('multiple'=>'multiple', 'size'=>5)); ?>
<?php echo $form->error($model,'maincat_id'); ?>
</div>
我的卖方控制器
$model = new ProductSeller;
$this->render('insertItems', array('model'=>$model));
if(isset($_POST['ProductSeller']))
{
$model->attributes=$_POST['ProductSeller'];
if($model->save())
$this->redirect(array('view','id'=>$model- >sel_id));
$this->redirect(array('view','id'=>$model->pro_id));
}
卖方模型
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'productSellers' => array(self::HAS_MANY, 'ProductSeller', 'sel_id'),
);
}
产品模型 public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'productSellers' => array(self::HAS_MANY, 'ProductSeller', 'pro_id'),
);
}
ProductSeller模型public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'pro' => array(self::BELONGS_TO, 'Product', 'pro_id'),
'sel' => array(self::BELONGS_TO, 'Seller', 'sel_id'),
);
}
我应该遵循哪些步骤来保存pro_id和sel_id到数据库?谢谢0
你的动作应该是这样的:
$model = new ProductSeller;
if(isset($_POST['ProductSeller'])){
$is_valid = true;
$list = array();
foreach( $_POST['ProductSeller']['pro_id'] as $pro_id ) {
$list[ $pro_id ] = new ProductSeller;
$list[ $pro_id ]->setAttributes(array(
'sel_id' => $_POST['ProductSeller']['sel_id'],
'pro_id' => $pro_id,
));
$is_valid = $list[ $pro_id ]->validate() && $is_valid;
}
if ( $is_valid ) {
foreach( $list as $m ) {
$m->save(false);
));
$this->redirect(/*...*/);
}
}
$this->render('insertItems',array('model'=>$model));