我有这个代码,是一个自相关的表:
类别模型
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
}(...)
]
}
为什么查询会这样做?
答案 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的帮助