我在存储用户ID的表中有一个列名创建者。在获取记录时,我正在使用属于关系。我接收到数据,但无法显示。
注意:This thread doesn't solve my issue
类别表方案
Schema::create('categories',function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('slug')->unique();
$table->string('banner')->nullable();
$table->boolean('status')->default(false);
$table->bigInteger('creator');
$table->bigInteger('moderator');
$table->timestamps();
});
用户表方案
Schema::create('users',function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
类别模型:
public function creator(){
return $this->hasOne(User::class,'id','creator')->select('id','name');
}
类别控制器代码:
$records = Category::with(['creator'])->paginate(env('REC_LIMIT'));
我得到的数据:
"data":[{"id":1,"name":"Uncategorized","slug":"uncategorized","banner":null,"status":1,"creator":{"id":1,"name":"demon slayer"},"moderator":1,"created_at":"2019-11-03 12:08:33","updated_at":"2019-11-04 11:11:01"},
请注意,如果在查询中删除了with子句,则会得到:
"data":[{"id":1,"creator":1,
在刀片文件中,我正在执行以下代码,以打印创建者用户名而不是其记录ID。
$record->creator->name
//or
$record->creator[0]->name
目前我明白了:
Facade\Ignition\Exceptions\ViewException
Trying to get property 'name' of non-object (View: /Users/dragonar/Dev/pdp/resources/views/backend/category/index.blade.php)