문제

I am creating a web application that stores user's journeys and I'm build this application in CakePHP 2.2.5.

I have a Journey model and that journey model has many coordinate objects which store the lat long coordinates.

I'd like to send an API call to the journey's add method containing json in the body to create a new object.

I've tried to find out how to format the JSON to allow the controller to use it but I cant seem to find out. I'd also like to know how to add the child objects to the JSON.

I am testing the method using this cURL command

curl -i -H "ACCEPT: application/json" -X POST --data @/home/sam/data.json http://localhost/journeys/add.json

Running this CURL command create a blank entry in the database.

The JSON file included in the CURL contains

{"description" : "Hello World", "user_id":3}
도움이 되었습니까?

해결책 2

I've done some more research and found a solution to my problem:

CakePHP will save JSON data and it will also save nested model information.

$data = $this->request->input('json_decode');

Which is similar to what @Arash said but it will also save nested model information by calling

$this->Journey->saveAssociated($data)

The JSON I'm providing to the controller looks like:

{"Journey":
{"description":"Not even an article from the map", "user_id":3}, 
"Coordinate":[
    {"lat":54.229149, "lng":-5.114115},
    {"lat":54.39153, "lng":-5.114113}
 ]
}

Where coordinate belongs to Journey.

다른 팁

It's better to convert json to array(with json_decode function) then manipulate your array, If you want at last convert it to json(json_encode function).

cakePHP handle this task by : JsHelper::object

edit 1: but I think when php do it for you , it's better use php pure function instead of cakePHP functions.

edit 2: I think cakePHP doesn't handle it , you should handle it by yourself, convert your json to array, change your array as you want in foreach then pass it to saveAll function to insert or update in database.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top