Php 如何在Yii框架中添加新操作?
我们这个PHP应用程序已经不使用任何框架了。我们正在利用Yii框架为我们的简单移动应用程序构建Web服务。我们对Yii框架还很陌生 我们遵循这篇文章并设法开始工作- 主要是它刚刚创建了ApiController.php并扩展了控制器类 数据库中有3个表:Category、Subcategory和Ad。 表中的关系如下所示:Php 如何在Yii框架中添加新操作?,php,yii,Php,Yii,我们这个PHP应用程序已经不使用任何框架了。我们正在利用Yii框架为我们的简单移动应用程序构建Web服务。我们对Yii框架还很陌生 我们遵循这篇文章并设法开始工作- 主要是它刚刚创建了ApiController.php并扩展了控制器类 数据库中有3个表:Category、Subcategory和Ad。 表中的关系如下所示: 类别有许多子类别 子类别有许多广告 默认情况下,在执行CRUD过程之后,它会生成类别、子类别和Ad的代码。我们遇到的问题是,此代码会将actionList生成为选择整个记录
- 按类别ID列出子类别
- 按子类别ID列出广告
// {{{ actionList
public function actionList()
{
// $this->_checkAuth();
switch($_GET['model'])
{
case 'category': // {{{
$models = Category::model()->findAll();
break; // }}}
case 'ad': // {{{
$models = Ad::model()->findAll();
break; // }}}
case 'subcategory': // {{{
$models = Subcategory::model()->findAll();
break; // }}}
default: // {{{
$this->_sendResponse(501, sprintf('Error: Mode <b>list</b> is not implemented for model <b>%s</b>',$_GET['model']) );
exit; // }}}
}
if(is_null($models)) {
$this->_sendResponse(200, sprintf('No items where found for model <b>%s</b>', $_GET['model']) );
} else {
$rows = array();
foreach($models as $model)
$rows[] = $model->attributes;
$this->_sendResponse(200, CJSON::encode($rows));
}
} // }}}
/{{{{actionList
公共功能操作列表()
{
//$this->_checkAuth();
开关($\u GET['model'])
{
案例“类别”:/{{{
$models=Category::model()->findAll();
中断;/}}
案例'ad'://{{{
$models=Ad::model()->findAll();
中断;/}}
案例“子类别”://{{
$models=子类别::model()->findAll();
中断;/}}
默认值://{{
$this->_sendResponse(501,sprintf('Error:Mode list未为模型%s'实现,$_GET['model']);
退出;//}
}
如果(为空($models)){
$this->_sendResponse(200,sprintf('s型没有找到项目,$_GET['model']);
}否则{
$rows=array();
foreach($models作为$model)
$rows[]=$model->attributes;
$this->_sendsresponse(200,CJSON::encode($rows));
}
} // }}}
非常感谢您的帮助。您可以如下迭代子类别(在生成的代码中命名变量)$类别是加载的模型,您将为其显示子类别
foreach($category->subcategories as $subcategory)
{
// you have your subcategory
}
同样,你也可以用同样的方法迭代广告:
foreach($subcategory->ads as $ad)
{
// you have all ads under this subcategory
}
您可以将第二个代码放在第一个代码中,以获得所有代码
这可以是视图或控制器,取决于您想如何显示…谢谢@Malkocglu。我添加了一个示例代码,以便您可以查看。旁注:不要在(每个)操作中使用类似于
$this->\u checkAuth()
的结构,请为此使用感谢PeterM-可以。顺便提一下我会使用Gii自动创建模板代码并复制这些示例<代码>http://localhost/web/gii