尝试在Yii2高级模板中重铸Yii 1.1应用程序,并在视图中显示相关模型数据。
已经搜索过有关此问题的答案,但据我所知,我正在遵循Yii2协议收集数据,而我见过的其他扩展示例都与例如GridView的
相关型号代码:
前端/配置/ main.php
return [
...
'components' => [
...
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules'=> [
'home' => 'page/home',
'<alias:about>' => 'page/page',
'page/<alias>' => 'page/page'
],
],
公共/模型/ page.php文件
namespace common\models;
use Yii;
/**
* This is the model class for table "page".
...
* The followings are the available model relations:
* @property Content[] $contents
*/
class Page extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'page';
}
...
public function getContents()
{
return $this->hasMany(Content::className(), ['pageId' => 'id']);
}
...
模型/普通/ Content.php
namespace common\models;
use Yii;
/**
* This is the model class for table "content".
...
* The followings are the available model relations:
* @property Page $page
*/
class Content extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'content';
}
...
public function rules()
{
return [
[['name', 'slug', 'pageId', 'content'], 'required'],
[['pageId'], 'integer'],
[['content'], 'string'],
[['name', 'slug'], 'string', 'max' => 255],
[['pageId'], 'exist', 'skipOnError' => true, 'targetClass' => Page::className(), 'targetAttribute' => ['pageId' => 'id']],
];
}
...
public function getPage()
{
return $this->hasOne(Page::className(), ['id' => 'pageId']);
}
前端/控制器/ PageController.php
class PageController extends Controller
{
...
public function actionPage($alias)
{
$model=$this->loadContent($alias);
if ($alias == "home")
{
$news=$this->loadRecentNews();
}
$this->render('default',[
'model'=>$model,
'news'=>$news
]);
}
...
public function loadContent($page)
{
$pageModel = Page::find()->where(['slug'=>$page])->with('contents')->all();
if($pageModel===null)
throw new CHttpException(404,'The requested Page could not be found.');
return $pageModel;
}
public function loadRecentNews()
{
$newsModel = News::find()->orderBy('create_time DESC')->limit(2)->all();
return $newsModel;
}
frontend / views / page / default.php(失败的部分)
<?php foreach ($model->contents as $content) { ?>
<h3><?php echo $content->name; ?></h3>
<?php echo $content->content; ?>
<?php } ?>