用 Cakephp 中的相关数据替换外键



我有一个Cakephp应用程序,它使用containable来允许我轻松获取相关数据。现在这很好用,并且确实拉下了我正在寻找的所有数据。问题是它创建了主模型的同级,而不是将相关数据嵌套在里面。我在下面包含了当前查询返回的内容与我希望返回的内容。

电流防爆:

{
    'Product' :
    {
        'id':321
        'name':'product name'
        'store_id':123
    },
    'Store' :
    {
        'id':123
        'name':'store name'
    }
}

期望的前任:

{
    'Product' :
    {
        'id':321
        'name':'product name'
        'store': {
            'id':123,
            'name':'store name'
        }
    }
}

你可以使用 CakePHP 的 afterFind 模型方法:

class Product extends AppModel{
    function afterFind($results,$primaryKey){
        unset($results['Product']['store_id']);
        $results['Product']['store'] = $results['Store'];
        return $results;
    }
}

请注意,传递给方法的 $results 参数是 find默认返回的数组,我们在 afterFind 方法中返回的数组是 find 将返回的数组......

在这种情况下,afterFind()回调不是一个好主意,除非您希望随时随地修改结果。此外,在更改结构之前,还需要检查关联的模型数据是否可用。

阅读这两个链接:

  • http://book.cakephp.org/2.0/en/views/json-and-xml-views.html
  • http://book.cakephp.org/2.0/en/views/json-and-xml-views.html#using-a-data-view-with-view-files

序列化视图变量并使用 json 视图,并根据需要更改数据。

取自书中的例子:

// Controller code
class PostsController extends AppController {
    public function index() {
        $this->set(compact('posts', 'comments'));
    }
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
    unset($post['Post']['generated_html']);
    // MODIFY YOUR DATA HERE AS NEEDED
}
echo json_encode(compact('posts', 'comments'));

不要忘记设置扩展路由并使用 RequestHandlerComponent。阅读我提供的链接,它们解释得很好。

我最终创建了自己的帮助程序,该助手足够通用,可用于所有类型的数据。这将搜索主结果并查找_id键,然后查找与要组合的 id 匹配的模型。

<?php
App::uses('AppHelper', 'View/Helper');
class DataMapperHelper extends AppHelper {
    public function combineMultipleResults($dataArray) {
        return Hash::map($dataArray, "{n}", array($this, 'combineResults'));
    }
    public function combineResults($dataArray) {
        reset($dataArray);
        $primaryKey = key($dataArray);
        foreach ($dataArray[$primaryKey] as $key => $value) {
            if(preg_match("/[a-zA-Z]+_id/", $key) == 1) {
                $newKey = str_replace("_id", "", $key);
                $linkedDataKey = ucfirst($newKey);
                $dataArray[$primaryKey][$newKey] = $dataArray[$linkedDataKey];
                unset($dataArray[$primaryKey][$key]);
                unset($dataArray[$linkedDataKey]);
            }
        }
        return $dataArray[$primaryKey];
    }
}

相关内容

最新更新