[英]LARAVEL - I want to access the main category from the category object with the upper _id column that contains the main category ID
I want to access the main category from the category object with the upper _id column that contains the main category ID. 我想从类别对象使用包含主要类别ID的上部_id列访问主要类别。
Error: Cannot use object of type Illuminate\\Database\\Eloquent\\Relations\\BelongsTo as array 错误:无法将类型为Illuminate \\ Database \\ Eloquent \\ Relations \\ BelongsTo的对象用作数组
Categories migration : 类别迁移:
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('upper_id')->default(0);
$table->string('name', 100);
$table->string('slug', 100);
$table->string('description', 500)->nullable();
$table->timestamps();
$table->softDeletes();
});
Category model : 类别型号:
class Category extends Model{
use SoftDeletes;
protected $fillable = ['upper_id', 'name', 'description', 'slug',];
public function companies()
{
return $this->hasMany('App\Company', 'category_id', 'id');
}
public function up_category()
{
$category = $this->belongsTo('App\Category', 'upper_id', 'id');
return $category['name'];
}
CategoryController : CategoryController:
public function index()
{
$categories = Category::where('deleted_at', null)->get();
return view('admin.category.index', compact('categories'));
}
View : 查看:
@foreach($categories as $category)
<tr>
<td>{{ $category->name }}</td>
<td>{{ $category->up_category->name }}</td>
</tr>
@endforeach
change in your model function up_category 更改模型函数up_category
public function up_category(){
return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
'name' => '-'
]);
}
Blade file correct. 刀片文件正确。
<td>{{ $category->up_category->name }}</td> //No change
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.