繁体   English   中英

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

[英]Vue.js and Laravel difference return json and resource

我对两者之间的区别感到困惑。 似乎它们提供相同的功能。 这是每个控制器外观的示例。

返回 json 控制器

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

返回资源控制器

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 mutators: https ://laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting

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

<?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 记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM