Home >Backend Development >PHP Tutorial >Yii2.0 uses AR joint table query method to share
There are two ways to use joint table query in Yii2.0. The first is Query Builder, and the second is using Active Record. The Chinese website talks about query builder in detail. AR is very deceptive. This article mainly introduces Yii2.0 to use AR joint table query examples. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Two tables
{{%article}} and {{%article_class}}
{{%article}} .article_class association { {%article_class}}.id
1. To use AR to perform associated queries, first create an association in models {Article}:
class Article extends \yii\db\ActiveRecord { //这里声明被关联字段 public $class_name; /** * @inheritdoc */ public static function tableName() { return '{{%article}}'; } ... //关联 mysite_article_class 表 public function getArticleClass(){ /** * 第一个参数为要关联的子表模型类名称, * 第二个参数指定通过子表的 id 去关联主表的 article_class 字段 */ return $this->hasMany(ArticleClass::className(), ['id' => 'article_class']); } }
2. Use in controllers {ArticleController},
public function actionIndex() { $article = new Article(); if(Yii::$app->request->get('class')){ $query = Article::find() ->joinWith('articleClass') ->select(['{{%article}}.*,{{%article_class}}.class_name']) ->where(['article_class' => Yii::$app->request->get('class')]); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); }else{ $query = Article::find() ->joinWith('articleClass') ->select(['{{%article}}.*,{{%article_class}}.class_name']); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); } return $this->render('index', [ 'dataProvider' => $dataProvider, 'model' => $article, ]); }
3. Use
<?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', //'article_content:ntext', [ 'value'=>'class_name', 'label'=>'文章分类', ], 'article_title', 'article_addtime:datetime', // 'article_updatetime:datetime', // 'article_author', ['class' => 'yii\grid\ActionColumn'], ], ]); ?># in view {GridView} ##Related recommendations:
MySQL joint table query detailed explanation_MySQL
##MySQL joint table query optimization actual operation processYii2 joint table query cannot check individual fields?The above is the detailed content of Yii2.0 uses AR joint table query method to share. For more information, please follow other related articles on the PHP Chinese website!