Skip to content

Commit 736a620

Browse files
committed
add update relationships action
1 parent ab52bba commit 736a620

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

src/UpdateRelationshipAction.php

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,43 @@
77

88
namespace tuyakhov\jsonapi;
99

10-
11-
use yii\helpers\Inflector;
10+
use yii\db\BaseActiveRecord;
1211
use yii\rest\Action;
12+
use yii\web\BadRequestHttpException;
1313
use yii\web\ServerErrorHttpException;
1414

1515
class UpdateRelationshipAction extends Action
1616
{
17+
/**
18+
* @param $id
19+
* @param $name
20+
* @throws BadRequestHttpException
21+
* @throws ServerErrorHttpException
22+
*/
1723
public function run($id, $name)
1824
{
25+
/** @var BaseActiveRecord $model */
1926
$model = $this->findModel($id);
2027

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);
2347
}
2448

2549
throw new ServerErrorHttpException('Failed to update the relationship for unknown reason.');

0 commit comments

Comments
 (0)