Mik*_*tes 5 php arrays json dao yii
嗨那里只是问题
我正在为一个在前端使用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'];
}
}
Run Code Online (Sandbox Code Playgroud)
这是我想要的回归到目前为止,但它是实现后续的最有效的方法吗?
如果您不想使用 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'];
}
Run Code Online (Sandbox Code Playgroud)
这比执行一个查询来检索所有客户,然后执行 N 个查询来获取其品牌(其中 N 是客户数量)要高效得多。您还可以加入第三个表projects并检索每个品牌的所有相关项目。
| 归档时间: |
|
| 查看次数: |
10652 次 |
| 最近记录: |