[英]How to merge 2 objects in Laravel and Vue.Js
我嘗試在 Laravel + Vue.JS(Vuex 也是)中創建一個簡單的 CRUD 應用程序我有一個小問題實際上是什么問題我有一個表格“類別”這個表格的結構你可以在屏幕截圖上看到
我創建了 2 個測試行,你可以在屏幕截圖上看到我如何插入標題而不是值 parent_id 如果 parent_id 具有像某人 ids 的值我在 Vue Componetn 和 v-if 中嘗試 v-for 但我沒有任何結果這是我的代碼:
<tr v-for="(category, $index) in categories" :key="category.id">
<td>{{$index + 1}}</td>
<td>{{category.title}}</td>
<td v-if="category.parent_id === null">Category</td>
<td v-else>SubCategory</td>
<td>{{category.created_at | moment("DD, MMMM, YYYY")}}</td>
<td></td>
</tr>
這是我從控制器獲得的數據
無論如何感謝您的幫助
解決方案是定義關系 hasOne 就像
public function parent()
{
return $this->hasOne(Category::class,'id','parent_id');
}
然后您可以定義資源,您可以在其中使用定義的關系聲明父級的標題,如下所示
$this->parent->title
使用命令創建資源
php artisan make:resource CategoryResource
然后在你的控制器中你應該使用資源
use App\Http\Resources\CategoryResource;
並在控制器的動作中提供響應,如
$categories = Category::paginate(15);
return CategoryResource::collection($results); // instead of response()->json($categories , 200);
並舉例說明您的資源應該是什么樣子
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CategoryResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'parent_id' => $this->parent_id,
'parent_title' => $this->parent->title,
...
];
}
}
您可以找到有關資源的信息https://laravel.com/docs/5.8/eloquent-resources
這是控制器的代碼
public function index()
{
$result = ['success' => true];
$category = Category::paginate(15);
$result['category'] = $category->items();
$result['pagination']['currentPage'] = $category->currentPage();
$result['pagination']['total'] = $category->total();
$result['pagination']['perPage'] = $category->perPage();
return response()->json($result, 200);
}
我認為渲染函數和數組處理必須在Vue Component
這是我的類別模型代碼
public function products()
{
return $this->hasMany('App/Products');
}
public function parent()
{
return $this->hasOne(Category::class,'id','parent_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.