0
我正在開發這個網站,要求我在一個視圖中合併兩個模型,他們之間有一對多的關係。模型名稱是家庭和圖像意義家有很多圖像,但圖像只有一個家。在Yii更新中獲取多個記錄
我已經管理結合在一起的觀點,但我遇到的問題是獲得所有的圖像。例如,我有6張圖片想要展示,或者我有5張圖片想展示。
家庭控制器UpdateMethod
public function actionUpdate($id)
{
$home=$this->loadModel($id);
$image=Image::model()->findByAttributes(array('homeId'=>$home->id));
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Home'],$_POST['Image'])){
$home->attributes=$_POST['Home'];
$image->attributes=$_POST['Image'];
$valid=$home->validate();
$valid=$image->validate() && $valid;
if($valid){
if($home->save()){
$image->save();
}
}
}
$this->render('update',array(
'home'=>$home,
'image'=>$image,
));
}
我_form.php這個加入他們一起
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'home-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>false,
)); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($home); ?>
<div class="row">
<?php echo $form->labelEx($image,'imageUrl'); ?>
<?php echo $form->textField($image,'imageUrl',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($image,'imageUrl'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($home,'recentEvents'); ?>
<?php echo $form->textField($home,'recentEvents',array('size'=>60,'maxlength'=>100)); ?>
<?php echo $form->error($home,'recentEvents'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($home,'introduction'); ?>
<?php echo $form->textArea($home,'introduction',array('rows'=>6, 'cols'=>50)); ?>
<?php echo $form->error($home,'introduction'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($home->isNewRecord ? 'Create' : 'Save'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
更新我所以現在它返回了FindByattribues,而不是在模型FindAllByAttribues數組。現在如何在視圖中處理該數組?
如果你建立了模型關係,你應該也可以使用'$ home-> images'(或者你調用關係)。這個關係應該是像這樣的''images'=>數組(self :: HAS_MANY,'Image','homeId')',它應該在home中定義。因此,在視圖中,您還可以使用'$ home-> images作爲$ image'或使用'$ images = $ home-> images'在控制器中定義圖像。並不是說你知道的方式是錯的,只是想把它扔到那裏。 http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship – Jeroen 2014-09-08 14:32:41
好的,謝謝你的建議! – Steve 2014-09-08 14:34:00