在我的代码中,我想在产品表的类别下显示类别和子类别
这是我的类别表
1。
public function up() { Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id'); //sub category id
$table->string('name');
$table->rememberToken();
$table->timestamps();
});
}
这是我的产品表
2。
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id');
$table->string('product_name');
$table->timestamps();
});
}
这是我的类别模型
3.Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model { protected $guarded=[];
public function products(){
return $this->hasMany('App\Product');
}
public function parent(){
return $this->belongsTo('App\Category');
}
}
这是我的产品型号
4.Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category(){
return $this->hasone('class::Category');
}
}
现在这是我的 ProductsController.php
5.ProductsController.php
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Product;
use Session;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function addproduct(Request $request){
$product=New Product();
$product->category_id=$request['category_id'];
$product->product_name=$request['product_name'];
$product->save();
return back()->with('success','product Upload Successfully!');
}
}
这是我的 addproduct.blade.php 文件
6.addproduct.blade.ph p
<form class="form-horizontal" method="post" action="{{route('add.product')}}" name="add_product" id="add_product" novalidate="novalidate">
@csrf
<div class="control-group">
<label class="control-label">main Category </label>
<div class="controls">
<select name="category_id" id="category_id" style="width:220px;">
@foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
@endforeach
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Product Name</label>
<div class="controls">
<input type="text" name="product_name" id="product_name">
</div>
</div>
<div class="form-actions">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
我想要这样的数据
鞋子 -休闲鞋 -正式鞋 移动 -Android移动版 -iphone T恤 -休闲T恤 -正式的T恤
这就是为什么我使用此代码 addproduct.blade.php
@foreach(App\Category::all() as $cat)
<option value="{{$cat->id}}" >{{ $cat->parent()->name ? $cat->parent()->name . ' -- ' : '' }}{{$cat->name}}</option>
@endforeach
但是当我应用此代码时,会出现错误,如下所示:-
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name (View: F:\laragon\www\flipcart\resources\views\admin\products\addproduct.blade.php)
答案 0 :(得分:0)
按照以下方式在“类别”模型中建立关系,然后尝试
public function parent(){
return $this->belongsTo('App\Category','parent_id','id');
}