Laravel 关系不适用于 belongsTo

Laravel Relationship not working with belongsTo

大家好,我只是将我的查询传递给通知 blade,但它给出了错误。我不知道我用波纹管代码做错了什么。如果你们解决了这个问题,我会很高兴。提前致谢

通知看到型号

<?php

namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class notificationseen extends Model
{
    use HasFactory;
    protected $table = 'notificationseens';

    public function Notification()
    {
        return $this->belongsTo(Notification::class, 'notificationID');
    }
}

通知模型

<?php

namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    use HasFactory;
    protected $table = 'notifications';

    public function notificationseen()
    {
        return $this->belongsTo(notificationseen::class, 'notificationID');
    }
}

查看Blade

 @foreach( $notification as $notify )

          @if($notify->Notification->seen == 0)
          <!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}" id="notifysee" data-id="{{ $notify->id }}">
            
            <div class="alert unread custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
              <div class="alert-text w-75">
                <h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
              </div>
            </div></a>
          @else
          <!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}">
          <div class="alert custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
              <div class="alert-text w-75">
              <h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
              </div>
            </div></a>

          @endif
        @endforeach 

Table结构

 $table->increments('id');
            $table->integer('userid');
            $table->integer('notificationID');
            $table->integer('seen')->default('0')->comment("0 for unseen 1 for seen");
            $table->timestamps();

你能帮帮我吗?我看不到任何问题,但它是我的错误“尝试在 null 上读取 属性“已看到””

您可以尝试添加一个isset来避免错误:

@if(isset($notify->Notification->seen) && $notify->Notification->seen == 0)
   (...)
@else
   (...)
@endif

编辑:在您的代码中,您定义了 2 个 belongsTo 方法,但根据 official Laravel documentation,您必须定义一个 hasOne 方法及其反函数 belongsTo方法。

好的,有些事情:

  1. 我会在 notificationseen class 中使用 belongsTo 除非一个 notificationseen 可以有多个 Notifications 属于;)

  2. Notification 是否有多个 notificationseen 引用?我不这么认为,所以在您的 Notification 中将引用更改为 hasOne

  3. 在你的 blade 中,使用 @if($notify->notificationseen->seen == 0) 或者你调用更好的 "Notification::with('notificationseen') ->get()" 在您的控制器中,然后将其传递给您的视图。