Sivabalan
Sivabalan

Reputation: 1131

How to display multiple model data in one single yii2 rest api action

I am using yii2 rest api. The problem in my action i have to display to model datas within one single action. I am displaying car details also type of cars and their available companies.

The problem is, car details in one model and the car types and car companies available on another two tables.

How to get the models using rest api.

Please someone suggest me on how to get this

Upvotes: 1

Views: 1610

Answers (2)

Salem Ouerdani
Salem Ouerdani

Reputation: 7886

You can use the extraFields method. Here is a an example:

class Image extends yii\db\ActiveRecord
{
    ...

    public function getOwner()
    {
        return $this->hasOne(Owner::className(), ['id' => 'owner_id']);
    }

    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->viaTable('image_has_tag', ['image_id' => 'id']);
    }

    public function getUploader() 
    { 
       return (new \yii\db\Query())
                ->select('username')
                ->from('user')
                ->where([ 'id' => $this->user_id ])
                ->scalar();
    }

    public function extraFields()
    {
        return ['owner','tags','uploader'];
    }
}

To get a list of images along with their respective owner, tags and uploader you can simply do a GET request to:

http:/localhost/images?expand=owner,tags,uploader

As you can see it is all about well designing relations in model classes. You may also use the fields method to unset or custum fields outputs in each related model class. See docs for more details.

Upvotes: 3

Igbanam
Igbanam

Reputation: 6082

I think Yii REST API only returns the vanilla CRUD operations in application data exchange formats (such as JSON). This would work for a basic REST service. But if you want custom data to be returned, you would have to manually write your REST responses.

Without Yii REST API, this can be achieved thus

  1. Process the request like you would a normal controller action
  2. Set the yii\web\Response accordingly: JSON, XML, and so on
  3. Make sure your response is HATEOAS compliant (if you're into that kinda thing; Yii 2 definitely is)
  4. Pack and return your response in the manner you wish.
  5. End the PHP process.

Upvotes: 0

Related Questions