[英]Yii framework: Using data from related Active Record models for searching
[英]best way to get related data from models in yii and return json
你好只是问题
我正在为一个在前端使用sproutcore的项目开发一个宁静的应用程序。
我的问题是,当需要返回 json 时,从 model 和其他相关模型中获取数据的最有效方法是什么。 我昨天读到它建议在使用 arrays 时使用 DAO 层,所以对于我的示例来说,这就是我目前所拥有的。
我有一份客户名单,每个客户都有 HAS_MANY 品牌,每个品牌都有 HAS_MANY 项目。 没有得到一个很好的客户群与他们的品牌继承人我所拥有的
$clients = Yii::app()->db->createCommand('select client.* from client where client.status = 1')->queryAll();
foreach($clients as $ckey => $client)
{
$clients[$ckey] = $client;
$brand_ids = Yii::app()->db->createCommand('select brand.id as brand_id, brand.client_id as b_client_id from brand where brand.client_id ='.$client['id'])->queryAll();
foreach($brand_ids as $bkey => $brand_id)
{
$clients[$ckey]['brands'][] = $brand_id['brand_id'];
}
}
到目前为止,这正在返回我想要的东西,但这是实现我所追求的最有效的方法吗?
安装客户端model
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 "*"
}
}
设置品牌model
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 "*"
}
}
在您的操作中进行客户/品牌搜索 function
$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
)
)
...
)
*/
这是你想要的吗? 我意识到,如果您只想要 select 品牌 ID(没有其他数据),您可以通过 sql 和GROUP_CONCAT (MySQL)和 select 搜索所有品牌 ID 的客户。 1,2,3,4,5,20,45,102
。
我意识到这已经过时了,但我自己也在寻找解决方案,我认为这是一个很好的解决方案。
在我的基础 Controller class (protected/Components/Controller.php) 我添加了以下函数:
protected function renderJsonDeep($o) {
header('Content-type: application/json');
// if it's an array, call getAttributesDeep for each record
if (is_array($o)) {
$data = array();
foreach ($o as $record) {
array_push($data, $this->getAttributesDeep($record));
}
echo CJSON::encode($data);
} else {
// otherwise just do it on the passed-in object
echo CJSON::encode( $this->getAttributesDeep($o) );
}
// this just prevents any other Yii code from being output
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
protected function getAttributesDeep($o) {
// get the attributes and relations
$data = $o->attributes;
$relations = $o->relations();
foreach (array_keys($relations) as $r) {
// for each relation, if it has the data and it isn't nul/
if ($o->hasRelated($r) && $o->getRelated($r) != null) {
// add this to the attributes structure, recursively calling
// this function to get any of the child's relations
$data[$r] = $this->getAttributesDeep($o->getRelated($r));
}
}
return $data;
}
现在,在 object 或对象数组上调用 renderJsonDeep 将对 JSON 中的对象进行编码,包括您提取的任何关系,例如将它们添加到 DbCriteria 中的“with”参数。
如果子 object 有任何关系,则这些关系也将在 JSON 中设置,因为 getAttributesDeep 是递归调用的。
希望这可以帮助某人。
如果您不想通过with()
功能使用 CActiveRecord,那么您应该编写一个 SQL 查询加入brand
表。
$rows = Yii::app()->db
->createCommand(
'SELECT c.*, b.id as brand_id
FROM client c INNER JOIN brand b
WHERE c.status = 1 AND b.client_id = c.id')
->queryAll();
$clients = array();
foreach ($rows as row) {
if (!isset($clients[$row['id']])) {
$clients[$row['id']] = $row;
$clients[$row['id']]['brands'] = array();
}
$clients[$row['id']]['brands'][] = $row['brand_id'];
}
这比执行一次查询来检索所有客户,然后执行 N 次查询来获取他们的品牌(其中 N 是客户的数量)要高效得多。 您还可以加入您的第三个表projects
并检索每个品牌的所有相关项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.