|
7 | 7 |
|
8 | 8 | namespace tuyakhov\jsonapi;
|
9 | 9 |
|
10 |
| - |
11 |
| -use yii\helpers\Inflector; |
| 10 | +use yii\db\BaseActiveRecord; |
12 | 11 | use yii\rest\Action;
|
| 12 | +use yii\web\BadRequestHttpException; |
13 | 13 | use yii\web\ServerErrorHttpException;
|
14 | 14 |
|
15 | 15 | class UpdateRelationshipAction extends Action
|
16 | 16 | {
|
| 17 | + /** |
| 18 | + * @param $id |
| 19 | + * @param $name |
| 20 | + * @throws BadRequestHttpException |
| 21 | + * @throws ServerErrorHttpException |
| 22 | + */ |
17 | 23 | public function run($id, $name)
|
18 | 24 | {
|
| 25 | + /** @var BaseActiveRecord $model */ |
19 | 26 | $model = $this->findModel($id);
|
20 | 27 |
|
21 |
| - if ($model instanceof ResourceInterface) { |
22 |
| - \Yii::$app->getRequest()->getBodyParams(); |
| 28 | + if (!$model instanceof ResourceInterface) { |
| 29 | + throw new BadRequestHttpException('Impossible to update relationships for resource'); |
| 30 | + } |
| 31 | + |
| 32 | + $data = \Yii::$app->getRequest()->getBodyParams(); |
| 33 | + $relationships = []; |
| 34 | + foreach ($data as $modelName => $identifier) { |
| 35 | + if (!isset($identifier['id'])) { |
| 36 | + continue; |
| 37 | + } |
| 38 | + /** @var BaseActiveRecord $modelName */ |
| 39 | + if ($relationship = $modelName::findOne($identifier['id'])) { |
| 40 | + $relationships[] = $relationship; |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + if (!empty($relationships)) { |
| 45 | + $model->unlinkAll($name); |
| 46 | + $model->setResourceRelationship($name, $relationships); |
23 | 47 | }
|
24 | 48 |
|
25 | 49 | throw new ServerErrorHttpException('Failed to update the relationship for unknown reason.');
|
|
0 commit comments