数据表
article表
articleCategory表
在models\articleCategory.php中
<?php
namespace app\models;
use Yii;
use \yii\db\ActiveRecord;
/**
* This is the model class for table "yii2_article_category".
*
* @property string $id
* @property string $category
* @property string $create_at
* @property string $updata_at
*/
class ArticleCategory extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'yii2_article_category';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['create_at', 'updata_at'], 'safe'],
[['category'], 'string', 'max' => 15]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'category' => '栏目',
'create_at' => '创建时间',
'updata_at' => '修改时间',
];
}
public function getArticle(){
return $this->hasMany(Article::className(),['category_id'=>'id'])->asArray()->all();
}
}
在控制器controllers/articleCategoryController.php中
<?php
/**
* Created by PhpStorm.
* User: moka同学
* Date: 2016/07/27
* Time: 8:52
*/
namespace app\controllers;
use yii\web\Controller;
use app\models\Article;
use app\models\ArticleCategory;
class ArticleCategoryController extends Controller{
public function actionIndex(){
//$date = 'hello';
//根据栏目查询它的文章信息
$articleCategory = ArticleCategory::find()->where(['category'=>'心奇天下'])->one();
//$article = $articleCategory->hasMany('app\models\Article',['category_id'=>'id'])->asArray()->all();
//$article = $articleCategory->hasMany(Article::className(),['category_id'=>'id'])->asArray()->all();
//$article = $articleCategory->getArticle();
$article = $articleCategory->article;
var_dump($article);die();
return $this->render('index',[
'data'=>$date
]);
}
}
说明:
$article = $articleCategory->hasMany('app\models\Article',['category_id'=>'id'])->asArray()->all();
这句中的category_id为artile表中的,id为articleCategory表。注意先后顺序,可以理解为栏目中有很多文章,所以文章中的category_id需要对应栏目的id. asArray()是以数组的形式输出,如果没有则是对象。
对hasMany进行了封装,让其存在model中,可供多次使用。
结果
第二种 根据文章查询栏目信息
在model中,article的model中
//根据文章查询栏目的信息,hasOne()因为一个文章只属于一个栏目,一比一的方法
public function getArticleCategory(){
return $this->hasOne(ArticleCategory::className(),['id'=>'category_id'])->asArray();
}
在控制器中
//根据文章查询栏目信息
$article = Article::find()->where(['id'=>1])->one();
$articleCategory = $article->articleCategory;
var_dump($articleCategory);die();
结果: