Skip to content

Commit 944394c

Browse files
author
Shashank Jain
committed
Fix: filling issue for belongs to relation
1 parent 00aad3e commit 944394c

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

Diff for: src/ApiModel.php

+25
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,31 @@ public function fill(array $attributes = [])
242242
else if (method_exists($this, $key) && ((is_array($attribute) || is_null($attribute)))) {
243243
// Its a relation
244244
$this->relationAttributes[$key] = $attribute;
245+
246+
// For belongs to relation, while filling, we need to set relation key.
247+
$relation = call_user_func([$this, $key]);
248+
249+
if ($relation instanceof BelongsTo) {
250+
$primaryKey = $relation->getRelated()->getKeyName();
251+
252+
// If key value is not set in request, we create new object
253+
if (!isset($attribute[$primaryKey])) {
254+
$model = $relation->getRelated()->newInstance();
255+
}
256+
else {
257+
$model = $relation->getRelated()->find($attribute[$primaryKey]);
258+
259+
if (!$model) {
260+
// Resource not found
261+
throw new ResourceNotFoundException();
262+
}
263+
}
264+
265+
$relationKey = $relation->getForeignKey();
266+
267+
$this->setAttribute($relationKey, $model->getKey());
268+
}
269+
245270
unset($attributes[$key]);
246271
}
247272
}

Diff for: tests/DummyUserTest.php

-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,6 @@ public function testUserIndexWithFields()
2828
[
2929
'fields' => "id,name,email,age",
3030
]);
31-
// dump($this->app['router']->getRoutes()->get());
32-
dump($response->getContent());
3331

3432
$this->assertEquals(200, $response->status());
3533
}

0 commit comments

Comments
 (0)