0
我正在使用Laravel 5.2。 我有2 Eloquent Models喜歡這個 -顯示種類和子類別在Laravel
Category.php -
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories'; //Table Name
public $timestamps = false;
public $incrementing = false; //For Non integer Primary key
protected $primaryKey = 'name';
protected $fillable = [
'name'
];
public function SubCategory()
{
return $this->hasMany('App\SubCategory', 'category_id', 'id');
}
}
而且SubCategory.php -
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
protected $table = 'sub_categories'; //Table Name
public $timestamps = false;
protected $fillable = [
'category_id',
'name'
];
}
所以,現在如果我在控制器 - 調用此
return Category::with('SubCategory')->get();
我越來越像這個 -
[
{
"id": 3,
"name": "Beahan-Mueller",
"sub_category": [
{
"id": 27,
"category_id": 3,
"name": "Carroll Trail"
},
{
"id": 3,
"category_id": 3,
"name": "Davis Lake"
},
{
"id": 9,
"category_id": 3,
"name": "Lehner Ranch"
}
]
},
{
"id": 10,
"name": "Beahan, Stark and McKenzi",
"sub_category": [
{
"id": 1,
"category_id": 10,
"name": "Dibbert Summit"
},
{
"id": 18,
"category_id": 10,
"name": "Kris Mount"
}
]
}
]
所以,我可以告訴大家,子類別鏈接工作,對不對?
但我的問題是,如果我想使用與刀片值顯示像這個 -
控制器 -
return view('public.listing.main', [
'current_page' => 'Add Listing',
'categories' => Category::with('SubCategory')->get()
]);
查看 -
@foreach ($categories as $category)
<li class="no-border">
<label class="pull-left">
<input type="checkbox" name="cat_{{ $category->id }}" checked>
<strong> {{ $category->name }} (21)</strong>
</label>
<ul>
@foreach($category->sub_category as $sub_cat)
<li>
<label class="pull-left">
<input type="checkbox" checked value="{{ $sub_cat->id }}"> {{ $sub_cat->name }} (7)
</label>
</li>
@endforeach
</ul>
</li>
@endforeach
我發現像這樣的錯誤 -
任何人都可以請幫助,爲什麼我找到這個錯誤?
請做var_dump($ categories); die;在你的看法和顯示結果。 –