yii 如何从网格视图中的其他表中获取数据

how to get data from other tables in grid view in yii

我有一个名为 attendance 的模块,但其中的值来自其他 table 具有某些条件的模块。那么我如何才能获得其他 table 的 ID。我的代码如下:

模型是:

    if($type == 2)
    {
     $model = new Supplier(); 
    }
    elseif($type==3)
    {
     $model = new TruckingCompany();
    }
    elseif($type==4)
    {
     $model = new ServiceProvider();
    }
    elseif($type==5)
    {
     $model = new Landowner();
    }
    elseif($type==6)
    {
     $model = new Refiner();
    }
    elseif($type==8)
    {
     $model = new Worker();
    }
    elseif($type==9)
    {
     $model = new Trainer();
    }

现在我想更新这条记录

    array(
        'header'=>'Action',         
        'class' => 'CButtonColumn',
        'template'=>'{update}',
        'updateButtonUrl'=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))',
   );

现在我想为更新记录获取这些不同 table 的 ID,这些在所有 table 中都是不同的。我可以通过下面的行得到它:

 'updateButtonUrl'=> 'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))';

但这不是为所有 table 定义这些的正确方法,所以在这种情况下该怎么做......任何想法......我是 yii 的新手。

为什么不创建 URL 以及像

这样的模型
if($type == 2)
    {
     $model = new Supplier(); 
     $updateUrl = 'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))';
    }
    elseif($type==3)
    {
     $model = new TruckingCompany();
     $updateUrl = 'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))';
    }

渲染时将其传递给视图

$this->render('view',array('updateUrl'=>$updateUrl));

然后最后像

一样在视图文件中使用它
array(
        'header'=>'Action',         
        'class' => 'CButtonColumn',
        'template'=>'{update}',
        'updateButtonUrl'=>$updateUrl,
   );

除了的回答。我会把它写成 array 形式:

$types = array(
    1 => array("modelName"=>"Supplier","url"=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->id))'),
    2 => array("modelName"=>"TruckingCompany","url"=>'Yii::app()->createUrl("attendance/update", array("id"=>$data->supplier_master_id))'),
);

当然,您可以通过拆分 "url" 键来改进这一点,例如:

"url"=>array(
     "route"=>"attendance/update",
     "params"=>'"id"=>$data->id',
 )

这样你就可以这样传递了:

if(array_key_exists($type,$types)){ //Checks if you've defined the type.   
    $this->render('view',array(
            'updateUrl'=>$types[$type]['url'],
            'model'=>new $types[$type]['modelName'](), //Creates your object.
         )
    );
    return; //just to be sure.
}
throw new CHTTPException(404, "Type not Found!");

使用改进后的 "url" 键,您的视图将如下所示:

array(
    'header'=>'Action',         
    'class' => 'CButtonColumn',
    'template'=>'{update}',
    'updateButtonUrl'=>'Yii::app()->createUrl(' . $updateUrl['route'] . ', array(' . $updateUrl['params'] . '))',
);

这稍微清理了你的代码并去掉了巨大的 if statement/switch。

createUrl string 还是有点难看,所以如果你愿意,可以进一步改进。