LARAVEL - 我想从包含主要类别 ID 的上 _id 列的类别对象访问主要类别
LARAVEL - I want to access the main category from the category object with the upper _id column that contains the main category 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
改变你的模型函数up_category
public function up_category(){
return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
'name' => '-'
]);
}
Blade 文件正确。
<td>{{ $category->up_category->name }}</td> //No change
我想从类别对象访问主要类别,上面的 _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
改变你的模型函数up_category
public function up_category(){
return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
'name' => '-'
]);
}
Blade 文件正确。
<td>{{ $category->up_category->name }}</td> //No change