【问题标题】:laravel 5 self relationship to jsonlaravel 5自我与json的关系
【发布时间】:2016-02-16 21:24:43
【问题描述】:

我如何在 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 表和一个sub_category 表,你想要的只是如果你查看特定类别,那么它的 sub_category 将显示在那个特定的 json 中?如果我理解有误,请纠正我?

标签: mysql json laravel-5 eloquent query-builder


【解决方案1】:

我认为您的正确解决方案是

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: [],
}
]  

希望这会有所帮助。

【讨论】:

  • 我们这样做:返回 Category::with('subCategory')->get() 我收到此错误:找不到列:1054 Unknown column 'categories.category_id' in 'where Clause' ( SQL: select * from categories where categories.category_id
  • 我必须在以下位置添加 'id': public function Category() { return $this->belongsTo('\App\Category','id'); }
猜你喜欢
  • 2019-05-21
  • 2021-12-15
  • 2021-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多