首页 > 解决方案 > LARAVEL - 我想从包含主类别 ID 的上部 _id 列的类别对象访问主类别

问题描述

我想使用包含主类别 ID 的上部 _id 列从类别对象访问主类别。

错误:不能使用 Illuminate\Database\Eloquent\Relations\BelongsTo 类型的对象作为数组

类别迁移:

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

类别型号:

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

类别控制器:

public function index()
{
    $categories = Category::where('deleted_at', null)->get();
    return view('admin.category.index', compact('categories'));
}

看法 :

@foreach($categories as $category)
                        <tr>
                            <td>{{ $category->name }}</td>
                            <td>{{ $category->up_category->name }}</td>
                        </tr>
@endforeach

标签: phplaraveleloquentbelongs-tohas-one

解决方案


更改模型函数up_category

public function up_category(){
    return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
    'name' => '-'
   ]);
}

刀片文件正确。

 <td>{{ $category->up_category->name }}</td> //No change

推荐阅读