CRUD资源包含与RESTful JSON-API的MANY_MANY关系的子资源

时间:2013-02-08 09:47:35

标签: php crud yii

我将YII框架用于具有RESTfull JSON-API的Web应用程序和CRUD操作。对于API,我使用restfullyii扩展名。还有其他选择吗?

有三个表(User,Event和event_participant)与MANY_MANY关系。这是事件模型中的关系:

public function relations()
{
    return array(
        'participants' => array(
            self::MANY_MANY,
            'User',
            'event_participant(studiobooking, user)'
        )
    );
}

我想使用CRUD操作在一个请求中使用用户子资源CRUD事件。它适用于使用子资源获取资源。现在我想保存/更新/删除资源包含。子资源,例如带有此数据的POST请求:

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

这应该在Event表中创建新事件,并在“event_participant”表中使用参与者ID创建事件中的新id。这可能与YII框架有关吗?

1 个答案:

答案 0 :(得分:0)

你必须提出自己的代码才能做到这一点,但这是相对简单的。这是一个例子。注意:这是在StackOverflow编辑器中“编码”的,因此它不是生产就绪的,经过测试的代码:)

//in your Event model
public function associateWithParticipant(int $participantId)
{
    //you may check if the participant even exists before inserting it, but this is a detail
    $sql="INSERT INTO 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 your Event controller (or ApiController or whatsoever you are using)
public function actionCreateEvent()
{
    //if for any reason POST is not giving you any JSON try file_get_contents('php://input')
    if(isset($_POST['Event'])) {
        $data = CJSON::decode($_POST['Event']);
        //first, make sure this is transactional or an error while adding participants could leave
        //your db in an inconsistent state
        $tx = Yii::app()->db->beginTransaction();
        try {
            //create the event
            $event = new Event();
            $event->attributes = $data;

            //save it and if that works check if there is anything in the participants "array"
            if($event->save()) {
                if(isset($data['participants'])) {
                    //check if this is a correct JSON array
                    if(is_array($data['participants']) {
                        foreach($data['participants'] as $participantEntry) {
                            //add a new row to the pivot table
                            $event->associateWithParticipant($participantEntry['id']);
                        }
                    } else {
                        throw new CHttpException(400,'Participants has to be a JSON array');
                    }
                }
            }
            //commit the transaction as we are finished now
            $tx->commit();
        } catch (Exception $e) {
            //roll back the tx if an error occurred
            throw new CException("I've seen the horrors of bad coding")
            $tx->rollback();
        }
    }
}