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

hc2pp10m  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(268)

我正在为一个在前端使用SproutCore的项目开发一个REST风格的应用程序。
我的问题是,当需要返回JSON时,从一个包含其他相关模型的模型中获取数据的最有效方法是什么?我昨天读到,建议在使用数组时使用DAO层,所以对于我的示例,这就是我目前所拥有的。
我有一个客户列表,其中每个客户都有_MANY品牌,每个品牌都有_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'];
            }

    }

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

nzrxty8p

nzrxty8p1#

设置客户端模型

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为客户端在一行中用逗号分隔。1,2,3,4,5,20,45,102

d7v8vwbk

d7v8vwbk2#

如果您不想使用CActiveRecord的with()功能,那么您应该编写一个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,并检索每个品牌的所有相关项目。

3zwjbxry

3zwjbxry3#

我知道这是旧的,但我一直在寻找一个解决方案,我自己,我认为这是一个很好的。
在我的基本控制器类(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是递归调用的。
希望这能帮助到一些人。

相关问题