Yii中,使用viaTable方法进行关联,通过电影和电影类型示例。
需要建立三个表 电影表 电影类型关联表 类型表表
电影表(movies)
关联表(main)
类型表
电影模型
<?php
namespace api\modules\v1\models;
use api\modules\v1\models\main;
use api\modules\v1\models\typies;
use Yii;
/**
* This is the model class for table "move".
*
* @property int $id
* @property string $movies
* @property string $type
*/
class Movie extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'movie';
}
public function getInfo(){
// 32
return $this -> hasMany(typies::className(), ['t_id' => 't_id']) -> viaTable('main', ['m_id' => 'm_id']);
//21
}
/**
* @inheritdoc
*/
public function fields(){
return [
"m_id",
"电影名称"=>"movies",
"所属类型"=>function (){
$data = $this->info;
$arr = [];
foreach ($data as $v) {
$arr[] = $v->t_name;
}
$arr = implode(",",$arr);
return $arr;
},
];
}
}
类型模型
<?php
namespace api\modules\v1\models;
use Yii;
/**
* This is the model class for table "typies".
*
* @property int $id
* @property string $t_name
*/
class Typies extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'typies';
}
}
关联模型:
<?php
namespace api\modules\v1\models;
use Yii;
/**
* This is the model class for table "main".
*
* @property int $move_id
* @property int $types_id
* @property int $id
*/
class Main extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'main';
}
}
运行结果: