2013-06-20 72 views
0

關係數據我已經創建了一個控制器,用於檢索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(); 

我應該怎麼查詢關係數據cata_table1領域的產值從表1和cata_table2從表2 讓我結果查詢輸出具有'_id,名稱,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

u能使用關係發表您的模型TABLE_3我們可以做到這一點 – Ninad

+0

GII沒有產生關係? – Ninad

回答

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); 

檢查一些語法可能是不完美的答案呃

+0

感謝這一點,但在foreach循環中無法訪問關係,價值爲$ –

+0

再次爲您的TABLE_3模型生成模型並嘗試使用由gii工具生成的關係名稱 – Ninad

+0

如果$ value是特定記錄的對象,則Relation應該可訪問 – Ninad

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);