Touhami
Touhami

Reputation: 809

REST extra fields and join in Yii2

I have this schema in my database.

One mission have many timesheets and one time sheet have just one mission.

One position have many missions and one mission have just one position.

One order have many positions and one position have just one order.

And in my class that extends from yii\rest\IndexAction I have this code (in the prepareDataProvider() method):

$query = $timeSheetModel->find()
    ->distinct()
    ->joinWith("mission")
    ->joinWith("mission.position")
    ->joinWith("mission.position.order")
    ->where("public.order.id = $id");

$results = new ActiveDataProvider([
    'query' => $query,    
]);

return $results;

So how to personalise my extra fields to get a json with the following structure:

Upvotes: 4

Views: 5358

Answers (2)

user3845133
user3845133

Reputation:

To return specific fields, in your model for example you could override the fields method:

public function fields()
{
    return [
        'misson' => function($model) {
            return $model->mission->id; // or anything else from the mission relation
        },
        ... etc.
    ];
}

More info about the fields and extraFields methods is available in the yii2 doc - http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#fields

Upvotes: 3

Rx Seven
Rx Seven

Reputation: 529

Use ArrayDataProvider (http://www.yiiframework.com/doc-2.0/yii-data-arraydataprovider.html)

    $query = new \yii\db\Query();
    $query = $timeSheetModel->find()
        ->distinct()
        ->joinWith("mission")
        ->joinWith("mission.position")
        ->joinWith("mission.position.order")
        ->where("public.order.id = $id");

    $results = new ArrayDataProvider([
        'allModels' => $query->all(),
        // Add pagination information if required
    ]);

    $datas = $results->allModels;

    foreach($datas as &$data) {
        // Do your formatting here 
    }

    $results->allModels = $datas;

    return $results;

Upvotes: 0

Related Questions