php - 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
解决方案
更改模型函数up_category
public function up_category(){
return $this->belongsTo('App\Category', 'upper_id', 'id')->withDefault([
'name' => '-'
]);
}
刀片文件正确。
<td>{{ $category->up_category->name }}</td> //No change
推荐阅读
- python - 无法在用户模型中导入 restframework.generics
- mongodb - MongoDB:从多个嵌入式数组中查询单个文档?
- ballerina - 无法导入核心 Ballerina 模块
- shopify - Shopify 遗嘱主题更改变体以下拉选择如果超过 5 个产品
- javascript - 验证通过后不显示 jquery 验证模式
- java - 来自 mongo 模板的 Mongo 响应未正确映射到 java 对象
- google-apps-script - Google Apps 脚本属性会保留多长时间?
- c# - 尝试在 WPF 应用程序中合并样式时出现问题
- dax - Dax Function Power BI
- c# - SignalR for Desktop-Web 应用程序(C#、.NET/Azure、WinForms)