简体   繁体   中英

Yii2: Restful API Create & Update with relations

My RESTful API needs to store relational data that comes in from a JSON POST/PUT request:

The Address-table has many categories via table addresscategory_assignment:

public function getAddresscategories() 
{
   return $this->hasMany(TblAddresscategory::className(), ['id' => 'addresscategory_id'])
                ->viaTable('tbl_addresscategory_assignment', ['address_id' => 'id']); 
}

What´s the best way to read and save the relational data?

Yii2 supports relational REST only in a GET request but not within POST/PUT.

Address-JSON that comes in via REST PUT:

{
    "id": 1,
    "name": "Miller",

    "addresscategories": [
        {
            "id": 9,
            "categories": "customer"
        },
        {
            "id": 10,
            "gruppe": "reseller"
        }
    ]
}

The addresscategories already exist, I only need to read the relations and store them to tbl_addresscategory_assignment

One approach could be that you attach an active record event of EVENT_AFTER_INSERT to the model you are creating new entries on. Then, after the data gets inserted from the post/put, then you can create the assignment relationship based on the ID of the model that was just inserted.

Events would allow you to handle data without breaking out of the built-in REST url structure

Here is a quick example without knowing the table structure...

public function init()
{
    $this->on(ActiveRecord::EVENT_AFTER_INSERT, function ($event) {

        // Category ID just created
        $firstid = $event->sender->id;

        // Whatever the second ID is
        $secondid = 999;

        $assignment = new CategoryAssignment;
        $assignment->setAttribute('firstid', $firstid);
        $assignment->setAttribute('secondid', $secondid);
        $assignment->save();
    }
}

You can checkout this post discussing many-to-many relationships in a RESTful API. There's a lot of discussion about the best way to do this, but it really depends on what's best for your application.

For many-to-many relationships, I tend to create a resource for the relationship itself, in your case an addresscategory_assignment resource. This would represent entries in your tbl_addresscategory_assignment table and look something like this:

GET http://my.api/relationships/addresscategory_assignment

{
    table_id: 6,
    address_id: 15
    category_id: 2
}

Exposing the relationship this way has a few advantages:

  1. You can easily create/update the many-to-many relationships using this resource.
  2. If you add some sort of inactive/soft-delete field, you can inactivate old relationships and preserve relationship histories, which may or may not be important to you.
  3. You can really ignore these relationship resources unless you're creating/updating. You can get the related objects using Yii's relationship methods in the models and the extraFields method coupled with the expand GET parameter.

The downside is that there are now extra resources and you often have to make an extra API call or two to get things done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM