Explain how Yii2.0 uses AR tables to query instances, and explain how yii2.0ar instances
In Yii2.0, there are two ways to Query tables: Query Builder and Active Record ), the Chinese network is very detailed about the Query Builder, and AR is very boring. The following describes how to use it for your reference.
Two tables
{% Article }}and {% article_class }}
{% Article }}. article_class Association {% article_class}. id
1. To use AR for association query, first create association in models {Article:
Class Article extends \ yii \ db \ ActiveRecord {// declare the associated field public $ class_name;/*** @ inheritdoc */public static function tableName () {return '{{% article }}';}... // associate mysite_article_class table public function getArticleClass () {/*** the first parameter is the name of the subtable model class to be associated, * The second parameter specifies to associate the article_class field */return $ this-> hasMany (ArticleClass: className (), ['id' => 'Article _ class']);}
2. Use it 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' => 'document category',], 'Article _ title ', 'Article _ addtime: datetime', // 'Article _ updatetime: datetime', // 'Article _ author ', ['class' => 'yii \ grid \ ActionColumn '],],]);?>
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.