我创建了一个控制器,用于检索JSON格式的数据,我需要json格式的所有关系数据
我的数据库就像
TABLE_1
_id category1
1 fruit
2 vegetable
TABLE_2
_id type
1 winter
2 summer
TABLE_3
_id name cata_table1 cata_table2
1 apple 1 2
Here cata_table1 is foreign key to TABLE_1 and cata_table2 foreign key to TABLE_2
$sql="SELECT * from TABLE_3";
$command=$connection->createCommand($sql);
$row=$command->queryAll();
如何查询关系数据以从table1输出cata_table1字段的值,从table2输出cata_table2 所以我的结果查询输出有`_id,name,TABLE_1.category1,TABLE_2.type
model TABLE_3
class TABLE_3 extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'TABLE_3';
}
public function rules()
{
return array(
array('_id,name,cata_table1,cata_table2', 'required'),
array('_id, name, cata_table1, cata_table2', 'safe', 'on'=>'search'),
);
}
public function relations()
{
}
答案 0 :(得分:0)
试试这个
您可能在TABLE_3模型中有关系,如图所示
public function relations()
{
'relation1' => array(self::BELONGS_TO, 'TABLE_1', '_id'),
'relation2' => array(self::BELONGS_TO, 'TABLE_2', '_id'),
}
按照你上面所做的那样做,然后做这样的事情
$sql="SELECT * from TABLE_3";
$command=$connection->createCommand($sql);
$row=$command->queryAll();
$sample=array();
foreach($row as $key=>$value){
$sample=array('id'=>$value->id,'name'=>$value->name,'name1'=>$value->relation1->category1,'name2'=>$value->relation2->type)
}
之后编码为json
echo CJSON::encode($sample);
检查一些语法可能这不是完美答案
答案 1 :(得分:0)
创建像Ninad在TABLE_3模型中所说的关系:
public function relations(){
'relation1' => array(self::BELONGS_TO, 'TABLE_1', '_id'),
'relation2' => array(self::BELONGS_TO, 'TABLE_2', '_id'),
}
在行动中:
$results = array();
$models = TABLE_3::model()->with(array('table1','table2'))->findAll();
foreach($models as $model){
$results[] = array($model->name, $model->relation1->category1, $model->relation2->type);
}
echo json_encode($results);