[英]laravel 5 self relationship to json
我如何在laravel中查詢具有自相關關系的表。 我需要他以json格式返回一個查詢類別和子類別,例如:
['room':{
bed room:1,
kid room:2,
},
'living room ':{
sitting-room:3
}][1]
遷移故事:
public function up() {
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('subcategories_id')->unsigned()->nullable();
$table->foreign('subcategories_id')
->references('id')
->on('categories');
// ->onDelete('cascade');
});
}
我認為您的正確解決方案是
Category Model
class Cateogry extends Model {
public function subCategory(){
return $this->hasMany('\App\SubCategory');
}
}
SubCategory Model
<?php
class SubCategory extends Model {
public function Category(){
return $this->belongsTo('\App\Category');
}
}
在您的控制器中
SomeController
<?php
class SomeController extends Controller {
public function index(){
return Category::with('subCategory')->get()
}
}
輸出量
[
{
name: 'Category1'
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
subcategory: [
{
subcategory_name: 'subcategory1',
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
},
{
subcategory_name: 'subcategory2',
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00'
}
],
},
{
name: 'Category1'
created_at: '0000-00-00 00:00:00',
updated_at: '0000-00-00 00:00:00',
subcategory: [],
}
]
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.