rest api expand

This commit is contained in:
Kavalar 2024-10-07 11:31:16 +03:00
parent 160c381abc
commit 5fe6bd9629
3 changed files with 13 additions and 25 deletions

View File

@ -11,6 +11,12 @@ class RestController
protected Model $model; protected Model $model;
protected function expand(): array
{
return [];
}
#[NoReturn] public function actionIndex(): void #[NoReturn] public function actionIndex(): void
{ {
$request = new Request(); $request = new Request();
@ -29,7 +35,11 @@ class RestController
#[NoReturn] public function actionView($id): void #[NoReturn] public function actionView($id): void
{ {
$expand = $this->expand();
$model = $this->model->where("id", $id)->first(); $model = $this->model->where("id", $id)->first();
if ($expand){
$model->load($expand);
}
$res = []; $res = [];
if ($model){ if ($model){
$res = $model->toArray(); $res = $model->toArray();

View File

@ -14,30 +14,9 @@ class PostRestController extends RestController
$this->model = new Post(); $this->model = new Post();
} }
#[NoReturn] public function actionView($id): void protected function expand(): array
{ {
$model = $this->model->where("id", $id)->first(); return ["user"];
$model->load("user");
$res = [];
if ($model){
$res = $model->toArray();
}
$this->renderApi($res);
} }
#[NoReturn] public function actionDelete($id): void
{
$model = $this->model->where("id", $id)->first();
$model->load("user");
$res = [];
if ($model){
$res = $model->toArray();
}
$model->delete();
$this->renderApi($res);
}
} }

View File

@ -9,7 +9,6 @@ use kernel\modules\user\models\User;
* @property string $content * @property string $content
* @property string $title * @property string $title
* @property string $slug * @property string $slug
// * @property string $username
* @property int $user_id * @property int $user_id
* @method static where(int[] $array) * @method static where(int[] $array)
* @method static find($id) * @method static find($id)
@ -31,7 +30,7 @@ class Post extends Model
]; ];
} }
public function user() public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{ {
return $this->belongsTo(User::class); return $this->belongsTo(User::class);
} }