laravel后续关系问题

我在存储用户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) 

wwwoo00mv 回答:laravel后续关系问题

您尝试过代替

public function creator(){
    return $this->hasOne(User::class,'id','creator')->select('id','name');
}

此:

public function creator(){
    return $this->hasOne(User::class,'user_id')->select('id','name');
}

或将函数的名称从creator()更改为user()

然后在刀片服务器$record->user->name中。

这是我在laravel文档中发现的:

  

Eloquent根据模型名称确定关系的外键。在这种情况下,将自动假定Phone模型具有user_id外键。如果您希望重写此约定,则可以将第二个参数传递给hasOne方法:return $ this-> hasOne('App \ Phone','foreign_key');   Source

,

我最终将创建者重命名为creator_id,并且在模型中,功能为创建者。这样,我现在可以访问所需的数据$ record-> creator-> name或$ record-> creator-> id。

我想要的不是创建者从原始代码中重现我的ID,而是可以直接执行$ record-> creator-> name或$ record-> creator-> id。

本文链接:https://www.f2er.com/3166938.html

大家都在问