gpt4 book ai didi

javascript - Vue.js 和 Laravel 返回 json 和资源的区别

转载 作者:行者123 更新时间:2023-12-02 22:17:29 25 4
gpt4 key购买 nike

我对两者之间的区别感到困惑。它们似乎提供相同的功能。以下是每个 Controller 的示例。

返回json Controller

 public function index() {
$department = Department::orderBy('created_at', 'desc')->get();
return response()->json($department);
}

返回资源 Controller

public function index() {
$department = Department::orderBy('created_at', 'desc')->get();
return DepartmentResource::collection($department);
}

最佳答案

不同之处在于第一个方法会触发模型方法toArray

<?php

class Message
{
public function getExcerptAttribube() {
return '...'; // strip HTML, etc ...
}

public function toArray() {
return [
'id' => $this->id,
'title' => $this->title,
]
}
}

这使得在将模型转换为 JSON 时可以轻松地以编程方式隐藏、转换或附加属性。

这当然也可以通过 $appends、$hidden、$casts、$with 等修改器来完成。

Eloquent 变异者:https://laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting

带有资源的秒方法允许将该逻辑移动到单独的对象。

<?php

class MessageResource extends JsonResource
public function toArray($request) {
$message = $this->resource;
$message->load('user'); // auto-load relation
$message->append('excerpt'); // use $message->getExcerptAttribube() to make an excerpt
$message->append('is_read'); // use $message->getIsReadAttribute()

return $message;
}
}

这对于将大量业务逻辑移到模型本身之外非常有用。这也避免了每次使用 $with 时查询额外的 SQL 记录。

关于javascript - Vue.js 和 Laravel 返回 json 和资源的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59342220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com