1

私は、RESTfull JSON-API と CRUD 操作を備えた Web アプリケーション用の YII フレームワークを使用しています。API については、restfullyii拡張機能を使用します。代替手段はありますか?

MANY_MANY 関係を持つ 3 つのテーブル (User、Event、および event_participant) があります。これは、イベントモデルの関係です。

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

CRUD 操作を使用して、1 つの要求でユーザー サブリソースを使用してイベントを CRUD したいと考えています。サブリソースでリソースをGETするように機能します。ここで、リソースを含めて保存/更新/削除したいと思います。サブリソース、たとえば、次のデータを含む 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 に答える