Laravel 8 在同一模型之间建立 2 个关系

Laravel 8 make 2 relationship between the same model

所以,这是我在文件模型上的关系方法:

public function User()
{
    return $this->belongsTo(
        User::class,
        'user_id',
        'id'
    );
}

public function modify()
{
    return $this->belongsTo(
        User::class,
        'update_id',
        'id'
    );
}

This is my model table

这是我的模型迁移代码

public function up()
{
    Schema::create('files', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnUpdate()->cascadeOnDelete();
        $table->foreignId('update_id')->nullable()->references('id')->on('users');
        $table->foreignId('division_id')->constrained()->cascadeOnUpdate();
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('details');
        $table->timestamp('published_at')->nullable();
        $table->timestamps();
    });
}

这是我的查看代码:

@foreach ($files as $key=>$file)    
          <tr>
            <td>{{ $files->firstItem() + $key }}</td>
            <td>{{ $file->title }}</td>
            <td><a href="{{ route('Files.index', ['division'=>$file->division->slug, 'byUser'=>$byUser]) }}">{{ $file->division->name }}</a></td>
            <td>
                @if (auth()->user()->id == 1)
                    <a href="{{ route('Files.index', ['division'=>$division, 'byUser'=>$file->user->username]) }}">{{ $file->user->name }}</a>
                @else
                    {{ $file->user->name }}
                @endif
            </td>
            <td>{{ $file->created_at }}</td>
            <td>
                {{-- @foreach ($file->modify as $update) --}}
                    {{ dd($file->modify->name) }}

This is my page view look like after executing code above

更改此行后:

{{ dd($file->modify->name) }}

至:

{{ ($file->modify->name) }}

我收到以下错误:

错误异常 尝试获取非对象的 属性 'name'

您的数组中的第一个 $file 似乎设置了 modify 关系,但随后的 $file 缺少它。要么进行空检查,要么确保始终设置关系。