Laravel 5 Json有关系

时间:2016-03-01 12:46:42

标签: laravel laravel-5 laravel-5.1

我有这个代码,是一个自相关的表:

类别模型

class Cateogry extends Model {
    public function subCategory(){
        return $this->hasMany('\App\SubCategory');
    }
} 

子类别模型

<?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()
    }
} 

当我做返回Category :: with(&#39; subCategory&#39;) - &gt; get(); 他打印:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 43,
                    "name": "Quartos",
                    "subcategories_id": null
                }
            ]
        }
    {
        "id": 55,
        "name": "Jovenil",
        "subcategories_id": 2,
        "sub_category": [
            {
                "id": 55,
                "name": "Jovenil",
                "subcategories_id": 2
            }
        ]
    }

代替:

{
            "id": 43,
            "name": "Quartos",
            "subcategories_id": null,
            "sub_category": [
                {
                    "id": 50,
                    "name": "Casal",
                    "subcategories_id": 1
                }
                {
                    "id": 51,
                    "name": "Jovenil",
                    "subcategories_id": 2
                }(...)
            ]
        }

为什么查询会这样做?

2 个答案:

答案 0 :(得分:0)

试试这个并测试您的代码,并分享您的搜索结果

return Category::with('subCategory')->where('id',43)->get();

答案 1 :(得分:0)

我改变了这个:

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');
    }
} 

到此:

    class Subcategory extends Model {

        protected $table="categories";
        public $timestamps = false;

        public function Category() {
            return $this->belongsTo('\App\Category','id');
        }

    }

class Category extends Model {

    protected $table="categories";
    public $timestamps = false;

    public function subCategory() {
        return $this->hasMany('\App\Subcategory','subcategories_id');
    }

}

并且工作正常,感谢Qazi的帮助