从Yii中的模型中获取相关数据并返回JSON的最佳方式


Best way to get related data from models in Yii and return JSON

我正在为一个在前端使用SproutCore的项目开发RESTful应用程序。

我的问题实际上是,当需要返回JSON时,从具有其他相关模型的模型中获取数据的最有效方法是什么。我昨天读到,在使用数组时,建议使用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'];
            }
    }

到目前为止,这是在回报我想要的,但这是实现我追求的最有效的方式吗?

设置客户端型号

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)进行搜索,并在一行中为客户端选择所有品牌ID,用逗号分隔。CCD_ 1。

如果您不想使用使用with()功能的CActiveRecord,那么您应该编写一个连接brand表的SQL查询。

$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,检索每个品牌的所有相关项目。

我意识到这很旧,但我自己也在寻找解决方案,我认为这是一个很好的解决方案。

在我的基本控制器类(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;
}

现在,对对象或对象数组调用renderJsonDeep,将用JSON对对象进行编码,包括您提取的任何关系,比如将它们添加到DbCriteria中的"with"参数中。

如果子对象有任何关系,那么这些关系也将在JSON中设置,因为getAttributesDeep是递归调用的。

希望这能帮助到别人。