我想使用 laravel 5.6 中的 Resource 将关系数据导入 json
当我查询时,我得到response.data.created_by一个对象。(在框中标记的第一个数据) (我需要使用 API 资源的这种功能)
但是使用API 资源它只显示而id不是"created_by" object. (框内标注第二个数据)
*框内标注数据差异。
*数据是使用 eager fetch 获取的。response.response.data.created_by
网址:http://localhost:8000/api/product/unit
回复:
{
“数据”: [
{
“身份证”:1,
“单位”:“米”,
“符号”:“米”,
“十进制”:1,
+-------------------------------------------------- ---------------------------------+
|"created_by": { |
| “身份证”:1,|
| “名称”:“管理员”,|
| "电子邮件": "admin@gmail.com", |
| "api_token": "$2y$10$.c7eJGS6x/C8JN9Hd.Qc1OgPUS8txMDuIHjZNRRlHQVGrYbJcC5u", |
| "created_at": "2018-05-09 15:45:59", |
| “updated_at”:“2018-06-08 15:38:41”|
|}, |
+-------------------------------------------------- ---------------------------------+
“更新者”:{
“身份证”:1,
“名称”:“管理员”,
“电子邮件”:“admin@gmail.com”,
"api_token": "$2y$10$.c7eJGS6x/C8JN9Hd.Qc1OgPUS8txMDuIHjZNRRlHQVGrYbJcC5u",
"created_at": "2018-05-09 15:45:59",
“updated_at”:“2018-06-08 15:38:41”
},
"created_at": "2018-06-19 00:38:54",
“updated_at”:“2018-06-19 20:00:16”
}
],
“资源”:{
“数据”: [
{
“身份证”:1,
“单位”:“米”,
“符号”:“米”,
“十进制”:1,
+----------------+
|“创建者”:1,|
+----------------+
“更新者”:1,
“创建时间”:{
“日期”:“2018-06-19 00:38:54.000000”,
“时区类型”:3,
“时区”:“亚洲/加尔各答”
},
“更新时间”:{
"日期": "2018-06-19 20:00:16.000000",
“时区类型”:3,
“时区”:“亚洲/加尔各答”
}
}
]
}
}
单元控制器.php:
命名空间 App\Http\Controllers\Product;
使用 App\Models\Product\Unit;
使用 Illuminate\Http\Request;
使用 App\Http\Controllers\Controller;
使用 Illuminate\Support\Facades\Validator;
使用 App\Http\Resources\Product\UnitResourceCollection;
使用 App\Http\Resources\Product\UnitResource;
使用 Illuminate\Validation\ValidationException;
类 UnitController 扩展控制器 {
公共函数索引()
{
$units = Unit::with(['created_by', 'updated_by'])->get();
+-------------------------------------------------- -----+
|返回[ |
| '数据' => $units, |
| '资源' => 新的 UnitResourceCollection($units) |
|]; |
+-------------------------------------------------- -----+
}
}
单元型号:
命名空间应用\模型\产品;
使用 Illuminate\Database\Eloquent\Model;
类单元扩展模型
{
公共函数 created_by() {
return $this->belongsTo('App\User', 'created_by', 'id');
}
公共函数updated_by(){
return $this->belongsTo('App\User', 'updated_by', 'id');
}
}
UnitResource.php
<pre>
namespace App\Http\Resources\Product;
use App\Http\Resources\UserResource;
use Illuminate\Http\Resources\Json\JsonResource;
class UnitResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'unit' => $this->unit,
'symbol' => $this->symbol,
'decimal' => $this->decimal,
'createdBy' => $this->created_by,
'updatedBy' => $this->updated_by,
'createdAt' => $this->created_at,
'updatedAt' => $this->updated_at
];
}
}