There are two ways to use a query builder in Yii2.0, the first being the query builders, the second using activity records (active record), the Chinese web is very detailed to the Query Builder, and AR is the pit Daddy, This article mainly and we introduce Yii2.0 use AR Table Query example, small series feel very good, now share to everyone, also to everyone to do a reference. Follow the small series together to see it, hope to help everyone.
Two tables
{{%article}} and {{%article_class}}
{{%article}}. Article_class Association {{%article_class}}.id
1. To make an association query using AR, first create the association in models {article}:
Class Article extends \yii\db\activerecord { //here declares that the associated field is public $class _name; /** * @inheritdoc * * /public static function TableName () { return ' {{%article}} '; } ... Association mysite_article_class Table Public function Getarticleclass () { /** * The first parameter is the child table model class name to be associated with, * The second parameter specifies that the Article_class field of the primary table be associated with the ID of the child table * /return $this->hasmany (Articleclass::classname (), [' id ' = ' Article_class ']); } }
2, used 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 in view {GridView}
<?= gridview::widget ([ ' dataprovider ' + = $dataProvider, ' columns ' = = [ ' class ' = ' yii\grid\ ' Serialcolumn '], ' id ', //' Article_content:ntext ', [ ' value ' = ' class_name ', ' label ' and ' = ' Article category ', ' , ' article_title ', ' article_addtime:datetime ', //' Article_updatetime:datetime ', //' Article_author ', [' class ' = ' Yii\grid\actioncolumn '], ],?>