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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?