1

我将 YII 框架用于具有 RESTfull JSON-API 和 CRUD 操作的 Web 应用程序。对于 API,我使用restfullyii扩展。有替代方案吗?

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

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 框架可以做到这一点吗?

4

1 回答 1

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();
        }
    }
}
于 2013-02-12T11:25:39.310 回答