Friday, 15 May 2015

php - CRUD Resource incl Sub-Resource in MANY_MANY relation with RESTfull JSON-API -



php - CRUD Resource incl Sub-Resource in MANY_MANY relation with RESTfull JSON-API -

i utilize yii framework web-application restfull json-api , crud operations. api utilize restfullyii extension. there alternative?

there 3 tables (user, event , event_participant) many_many relation. relation in event model:

public function relations() { homecoming array( 'participants' => array( self::many_many, 'user', 'event_participant(studiobooking, user)' ) ); }

i want utilize crud operations crud event user sub-resource in 1 request. works resource sub-resource. want save/update/delete resource incl. sub-resource, illustration post request data:

{ "event": "eventname", "start": "2013-02-17 14:30:00", "end": "2013-02-17 16:00:00", "participants": [ { "id": "2" },{ "id": "3" }] }

this should create new event in event table , new id event participant ids in "event_participant" table. possible yii framework?

you'll have come own code this, relatively straight forward. here's example. note: "coded" in stackoverflow editor, not production ready, tested code :)

//in event model public function associatewithparticipant(int $participantid) { //you may check if participant exists before inserting it, detail $sql="insert tbl_event_participant_pivot (event_id, participant_id) values(:event_id,:participant_id)"; $command=yii::app()->db->createcommand($sql); $command->bindparam(":event_id",$this->id,pdo::param_int); $command->bindparam(":participant_id",$participantid,pdo::param_int); $command->execute(); } //in event controller (or apicontroller or whatsoever using) public function actioncreateevent() { //if reason post not giving json seek file_get_contents('php://input') if(isset($_post['event'])) { $data = cjson::decode($_post['event']); //first, create sure transactional or error while adding participants leave //your db in inconsistent state $tx = yii::app()->db->begintransaction(); seek { //create event $event = new event(); $event->attributes = $data; //save , if works check if there in participants "array" if($event->save()) { if(isset($data['participants'])) { //check if right json array if(is_array($data['participants']) { foreach($data['participants'] $participantentry) { //add new row pivot table $event->associatewithparticipant($participantentry['id']); } } else { throw new chttpexception(400,'participants has json array'); } } } //commit transaction finished $tx->commit(); } grab (exception $e) { //roll tx if error occurred throw new cexception("i've seen horrors of bad coding") $tx->rollback(); } } }

php crud yii

No comments:

Post a Comment