gpt4 book ai didi

php - 将下拉列表中的多个输入保存到数据库

转载 作者:行者123 更新时间:2023-11-29 02:54:53 25 4
gpt4 key购买 nike

我是 yii 的新手,我无法将多个选定的数据存储到数据库中。我的数据库“product”“seller”和“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>

我的卖家 Controller

$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));

关于php - 将下拉列表中的多个输入保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31647368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com