【YII2案例:中间表关联两张表】
路径:http://localhost/yii23_associationtable/web/index.php?r=hello/index
主页view/hello/index.php:
~~~
<h1>YII2中间表关联两张表</h1>
<h1>分类</h1>
<?php foreach ($data2 as $key => $data) : ?>
分类id:<?php echo $data->id; ?> | <?php echo $data->name; ?><br/>
<?php endforeach; ?>
<hr/>
<h1>文章</h1>
<?php foreach ($data3 as $key => $data) : ?>
文章:<?php echo $data->id; ?> | <?php echo $data->title; ?><br/>
<?php endforeach; ?>
<hr/>
<h1>中间表</h1>
<?php foreach ($data1 as $key => $data) : ?>
中间表id:<?php echo $data->id; ?> | 分类id:<?php echo $data->tags_id; ?> | 文章id:<?php echo $data->article_id; ?><br/>
<?php endforeach; ?>
<hr/>
<h1>分类为PHP的文章</h1>
<?php foreach ($filter as $key => $data) : ?>
<?php echo $data->id; ?> | <?php echo $data->title; ?><br/>
<?php endforeach; ?>
<hr/>
~~~
控制器controller/HelloController.php:
~~~
<?php
namespace app\controllers;
use yii\web\Controller;
use app\models\Article;
use app\models\Tags;
use app\models\Core;
class HelloController extends Controller {
public function actionIndex(){
$data1=Core::find()->all();
$data2=Tags::find()->all();
$data3=Article::find()->all();
$filter=Article::find()->joinWith('tags')->where(['name'=>'php'])->orderBy('article_id ASC')->all();
return $this->render('index', compact('data1', 'data2', 'data3', 'filter'));
}
}
~~~
模型model/Core:
~~~
<?php
namespace app\models;
use yii\db\ActiveRecord;
//中间表
class Core extends ActiveRecord
{
public static function tableName()
{
return 'core';
}
public function getTags(){
return $this->hasMany(Tags::className(),['id'=>'tags_id']) // 标签ID对应中间表tags_id
->viaTable('article',['id'=>'article_id']) // 文章ID对应中间表article_id
->asArray();
}
}
~~~
模型model/Article:
~~~
<?php
namespace app\models;
use yii\db\ActiveRecord;
// 文章
class Article extends ActiveRecord
{
public static function tableName()
{
return 'article';
}
public function getTags(){
return $this->hasMany(Tags::className(),['id'=>'tags_id']) // 标签ID对应中间表tags_id
->viaTable('core',['article_id'=>'id']) // 中间表article_id对应文章ID
->asArray();
}
}
~~~
模型model/Tags:
~~~
<?php
namespace app\models;
use yii\db\ActiveRecord;
// 标签
class Tags extends ActiveRecord
{
}
~~~
效果:
![](images/20180824023540.png)
源码下载:
链接:https://pan.baidu.com/s/1uVST-9pmiUZZUlvqS91DJA 密码:hbzp