Есть 3 таблицы - tbl_auto, tbl_file и tbl_model_file и, соответственно, 3 модели: Auto (авто), File (файлы), ModelFile (таблица для связки авто и файлов).
Прописаны следующие связи:
В модели Auto:
Код: Выделить всё
/**
* @return array relational rules.
*/
public function relations()
{
return array(
'modelFiles' => array(self::HAS_MANY, 'ModelFile', 'model_id'),
'KdFiles' => array(self::HAS_MANY, 'File', array('file_id'), 'through'=>'modelFiles'),
);
}
Код: Выделить всё
public function relations()
{
return array(
'modelFiles' => array(self::HAS_MANY, 'ModelFile', 'file_id'),
);
}
Код: Выделить всё
public function relations()
{
return array(
'file' => array(self::BELONGS_TO, 'File', 'file_id'),
'model' => array(self::BELONGS_TO, 'Auto', 'model_id'),
);
}
На странице обновления (контроллер actionUpdate) модели Auto в файле _form.php и была выведена таблица со списком всех моделей Auto со списком имеющихся файлов в каждом авто.
Внимание! Лицам, не привыкшим к нижеприведенному *овнокоду категорически запрещается дальнейший просмотр .
Код: Выделить всё
// загружаем все авто
if(empty($model->id))
$autos=Auto::model()->findAll();
else
$autos=Auto::model()->findAll('id!=:id',array(':id'=>$model->id)); // кроме текущего авто
if(!empty($autos))
{
// формируем массив из авто с файлами
$all_files = array();
foreach($autos as $auto)
{
$all_files[]=$auto;
$auto_files=$auto->KdFiles;
foreach($auto_files as $file)
$all_files[] = $file;
}
$itemsProvider = new CArrayDataProvider($all_files,array(
'pagination'=>false,
)
);
// загрузка файлов КД текущей модели авто
$auto=Auto::model()->findByPk($model->id);
$auto_files=$auto->KdFiles;
if(!empty($auto->KdFiles))
{
foreach($auto->KdFiles as $file)
$auto_files_kd[] = $file->name;
}
echo "<h2>Реестр изделий</h2>";
// EScrollableGridView - плагин, позволяющий фиксировать заголовки таблиц, используется вместо CGridView
$this->widget('EScrollableGridView', array(
'height' => '400',
'width' => '0',
'id' => 'itemGrid',
'dataProvider' => $itemsProvider,
'rowHtmlOptionsExpression' => 'empty($data->name) ? array("id"=>"auto_".$data->id) : array()',
'rowCssClassExpression'=>function($row, $data, $model) use ($basket){
global $auto_id;
$class = $row % 2 ? 'even' : 'odd';
if(!isset($data->name))
{
$auto = Auto::model()->findByPk($data->id);
if($auto)
{
if(isset($auto->model_number))
$auto_id = $auto->id;
}
}
if(isset($data->name))
$class .= ' kdfiles auto_'. $auto_id;
else
$class = 'auto';
return $class;
},
'columns' => array(
array(
'class' => 'CCheckBoxColumn',
'selectableRows' => 2,
'checkBoxHtmlOptions' => array(
'name' => 'Auto[auto_kd_drag][]',
),
'value'=>function($data, $row) use ($auto_files_kd){
if(!empty($data->name))
return $data->id;
else
return NULL;
},
'disabled'=>function($data, $row) use ($auto_files_kd){
if(!empty($data->name))
{
if(is_array($auto_files_kd))
return in_array($data->name, $auto_files_kd);
}
else
return 'disabled';
},
'checked'=>function($data, $row) use ($auto_files_kd){
if(!empty($data->name))
{
if(is_array($auto_files_kd))
return in_array($data->name, $auto_files_kd);
}
},
'htmlOptions'=>array( 'class'=>'center'),
),
array(
'header'=>'Код изделия',
'type'=>'raw',
'name'=>'model_name',
'value'=>'!empty($data->name) ? "<div class=button-column2>". CHtml::link($data->name,array(Yii::app()->createUrl("/file/". $data->id)),array("target"=>"_blank", "class"=>"update")). "</div>". $data->name : "$data->model_number"',
),
array(
'header'=>'Тип файла',
'type'=>'raw',
'value'=>'isset($data->file_type_id) ? FileType::model()->find("id=:fileTypeId", array(":fileTypeId"=>$data->file_type_id))->description : ""',
),
array(
'header'=>'Дата создания',
'type'=>'raw',
'value'=>'!empty($data->create_time) ? date("d.m.Y", strtotime($data->create_time)) : ""',
),
),
));
}
1. Как правильно выводить таблицу со связанными данными (т.е. у каждого авто свои файлы)?
2. Не получается сделать сортировку и фильтрацию. Как её сделать?