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']
            ]
        );     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符