laravel 5 与 json 的自我关系

laravel 5 self relationship to json

我如何在 laravel 中查询具有自我关系的 table。我需要他 return 一个查询类别和子类别作为 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: [],
}
]  

希望这对您有所帮助。