业务需要用到这个中间表三表关联,自己写个demo实现 分享一下
test_tags表
CREATE TABLE `test_tags` (
`id` int(10) NOT NULL ,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=DYNAMIC
;
INSERT INTO `test_tags` VALUES (1, 'php');
INSERT INTO `test_tags` VALUES (2, 'IT');
INSERT INTO `test_tags` VALUES (3, '编程');
test_article表
CREATE TABLE `test_article` (
`id` int(10) NOT NULL AUTO_INCREMENT ,
`title` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
AUTO_INCREMENT=1
ROW_FORMAT=DYNAMIC
;
INSERT INTO `test_article` VALUES (1, '测试文章');
test_core表
CREATE TABLE `test_core` (
`id` int(10) NOT NULL ,
`tags_id` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`article_id` int(10) NOT NULL ,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=DYNAMIC
;
INSERT INTO `test_core` VALUES (1, '1', 1);
INSERT INTO `test_core` VALUES (2, '2', 1);
在Article文章模型里设置关联
<?php
namespace frontend\models;
class Article extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'test_article';
}
public function getTags(){
return $this->hasMany(Tags::className(),['id'=>'tags_id'])
->viaTable('test_core',['article_id'=>'id'])
->asArray();
}
}
跑一跑看看效果
public function actionTest(){
$model=Article::findOne(1);
$data=$model->tags;
var_dump($data);
}
结果如下
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(3) "php"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(2) "IT"
}
}
$data=Article::find()->joinWith('tags')->asArray()->all();
var_dump($data);
结果:
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "1"
["title"]=>
string(6) "标题"
["tags"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(3) "php"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(2) "IT"
}
}
}
[1]=>
array(3) {
["id"]=>
string(1) "2"
["title"]=>
string(12) "测试文章"
["tags"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(2) "IT"
}
[1]=>
array(2) {
["id"]=>
string(1) "3"
["name"]=>
string(6) "编程"
}
}
}
}