設置客戶模型
class Client extends CActiveRecord
{
//...
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'brands' => array(self::HAS_MANY, 'Brand', 'client_id'),
);
}
//...
public function defaultScope() {
return array('select'=>'my, columns, to, select, from, client'); //or just comment this to select all "*"
}
}
設置品牌模型
class Brand extends CActiveRecord
{
//...
/**
* @return array relational rules.
*/
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'client' => array(self::BELONGS_TO, 'Client', 'client_id'),
);
}
//...
//...
public function defaultScope() {
return array('select'=>'my, columns, to, select, from, brand'); //or just comment this to select all "*"
}
}
做客戶端/品牌的搜索結果在您的動作功能
$clients = Client::model()->with('brands')->findAllByAttributes(array('status'=>1));
$clientsArr = array();
if($clients) {
foreach($clients as $client) {
$clientsArr[$client->id]['name'] = $client->name; //assign only some columns not entire $client object.
$clientsArr[$client->id]['brands'] = array();
if($client->brands) {
foreach($client->brands as $brand) {
$clientsArr[$client->id]['brands'][] = $brand->id;
}
}
}
}
print_r($clientsArr);
/*
Array (
[1] => Array (
name => Client_A,
brands => Array (
0 => Brand_A,
1 => Brand_B,
2 => Brand_C
)
)
...
)
*/
這是你想要的? 我意識到,如果你想只選擇品牌ID(在別的沒有更多的數據),你可以通過SQL和GROUP_CONCAT(MySQL的)搜索並用逗號分開一行選擇所有品牌的IDS客戶端。 1,2,3,4,5,20,45,102
。
如果您沒有CActiveRecord對象用於您的表「客戶端」,請先執行它(請參閱:http://www.yiiframework.com/doc/guide/1。1/EN/database.ar)。 ('brand') - > findByAttributes(array('status'=> 1));' –
( )然後你將能夠獲得簡單的數據: '$ clients = Client :: model() - >作爲im將要返回json是不是更好地與DAO層一起工作,因爲使用ar執行quries會返回比我需要更多信息的地獄。所以當我來編碼數組我結束了更多的對象比我需要返回?? –
如果我理解正確: 1)你可以編寫你想要選擇的列(拋出模型類'客戶端'並且關聯到'品牌') 2)接下來,在選擇這些後執行'foreach'語句 2.1)並像你在你的問題示例中那樣轉換爲json / 我仍然建議先爲表創建模型。我首先要做,如果我對錶格進行全局更改,我只改變我的模型類。 –