dqlk31541 2017-03-31 15:33
浏览 51
已采纳

使用Cakephp 3复杂的JSON

I am working on a project which involves passing data "profiles" via JSON to a web application. I am using Cakephp 3.0 and am very new to it. I store the profiles in a mysql database and can easily query for the data and put it into a basic JSON format with each row being a separate value in the JSON:

Controller.php:

....
public function getProfileData()
    {
        $uid = $this->Auth->user('id');
        $this->loadComponent('RequestHandler');
        $this->set('profile', $this->MapDisplay->find(
            'all',
            ['conditions' => 
                ['MapDisplay.user_id =' => $uid]
            ]
        )
        );
        $this->set('_serialize', ['profile']);
    }
....

get_profile_data.ctp:

<?= json_encode($profile); ?>

Which returns something like this:

{
"profile": [
    {
        "alert_id": 1,
        "alert_name": "Test",
        "user_id": 85,
        "initialized_time": "2017-03-24T00:00:00",
        "forecasted_time": "2017-03-24T00:10:00",
        "minimum_dbz_forecast": 0,
        "maximum_dbz_forecast": 10,
        "average_dbz_forecast": 5,
        "confidence_in_forecast": 0.99,
        "alert_lat": 44.3876,
        "alert_lon": -68.2039
    },
    {
        "alert_id": 1,
        "alert_name": "Test",
        "user_id": 85,
        "initialized_time": "2017-03-24T00:00:00",
        "forecasted_time": "2017-03-24T00:20:00",
        "minimum_dbz_forecast": 5,
        "maximum_dbz_forecast": 15,
        "average_dbz_forecast": 10,
        "confidence_in_forecast": 0.99,
        "alert_lat": 44.3876,
        "alert_lon": -68.2039
    },
    {
        "alert_id": 2,
        "alert_name": "Test2",
        "user_id": 85,
        "initialized_time": "2017-03-24T00:00:00",
        "forecasted_time": "2017-03-24T00:10:00",
        "minimum_dbz_forecast": 10,
        "maximum_dbz_forecast": 20,
        "average_dbz_forecast": 15,
        "confidence_in_forecast": 0.99,
        "alert_lat": 44.5876,
        "alert_lon": -68.1039
    },
    {
        "alert_id": 2,
        "alert_name": "Test2",
        "user_id": 85,
        "initialized_time": "2017-03-24T00:00:00",
        "forecasted_time": "2017-03-24T00:20:00",
        "minimum_dbz_forecast": 15,
        "maximum_dbz_forecast": 25,
        "average_dbz_forecast": 35,
        "confidence_in_forecast": 0.99,
        "alert_lat": 44.5876,
        "alert_lon": -68.1039
]
}

I am hoping to A) Easily call individual profiles instead of searching for unique profile ids and B) Only have to load one JSON file to get all profile contents. An output of something like this would be more ideal:

 {
"profile": [
    {
        "alert_id": 1,
        "alert_name": "Test",
        "initialized_time":"2017-03-24T00:00:00",
        "alert_lat": 44.3876,
        "alert_lon": -68.2039,
        "profile_data": [
            {
                "forecasted_time": "2017-03-24T00:10:00",
                "minimum_dbz_forecast": 0,
                "maximum_dbz_forecast": 10,
                "average_dbz_forecast": 5,
                "confidence_in_forecast": 0.99
            },
            {
                "forecasted_time": "2017-03-24T00:20:00",
                "minimum_dbz_forecast": 5,
                "maximum_dbz_forecast": 15,
                "average_dbz_forecast": 10,
                "confidence_in_forecast": 0.99
            }
        ]
    },
    {
        "alert_id": 2,
        "alert_name": "Test2",
        "initialized_time": "2017-03-24T00:00:00",
        "alert_lat": 44.5876,
        "alert_lon": -68.1039,
        "profile_data": [
            {
                "forecasted_time": "2017-03-24T00:10:00",
                "minimum_dbz_forecast": 10,
                "maximum_dbz_forecast": 20,
                "average_dbz_forecast": 15,
                "confidence_in_forecast": 0.99
            },
            {
                "forecasted_time": "2017-03-24T00:20:00",
                "minimum_dbz_forecast": 15,
                "maximum_dbz_forecast": 25,
                "average_dbz_forecast": 35,
                "confidence_in_forecast": 0.99
            }
        ]
    }
]
}

How would I go about querying my database and populating this JSON structure? Are there any Cakephp tools that help do this? Does reframing the JSON into this structure seem to make sense?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • duanli8577 2017-04-03 13:04
    关注

    Thanks to user ndm, I realized there were a few problems with my approach. I thought having all data in one table would simplify things, but in reality it would make things more complicated and require redundant data storage (eg, a latitude and longitude value stored for every profile entry, instead of just once in a separate table).

    ndm also mentioned

    You'd just have to set up the associations properly, and contain the associated >table in your find, and in case the property name for the association would be >profile_data, you wouldn't even have to modify the results at all.

    After altering the Table Model file, I had this for a new "ProfileDataTable.php" file:

    class ProfileDataTable extends Table
    {
    
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);        
    
        $this->setTable('profile_data');
    
        $this->setDisplayField('title');
        $this->setPrimaryKey('alert_id');
        $this->addBehavior('Timestamp');
    
        $this->belongsTo('AlertData', [
            'foreignKey' => 'alert_id'
        ]);
    }
    
    }
    

    And this for a new "AlertDataTable.php" file:

    class AlertDataTable extends Table
    {
    
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);
    
        $this->setTable('alert_data');
    
        $this->setDisplayField('title');
        $this->setPrimaryKey('alert_id');
        $this->addBehavior('Timestamp');
    
        $this->hasMany('ProfileData', [
            'foreignKey' => 'alert_id'
        ]);
    }
    
    }
    

    The important lines here being "belongsTo" and "hasMany".

    I then was able to alter my query and use "contain" to easily link the two tables together and get the JSON formatted exactly how I wanted:

    $this->AlertData->find(
            'all',
            ['conditions' => 
                ['AlertData.user_id =' => $uid],
            'contain' => 
                ['ProfileData']
            ]
        );     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?