首页 > 解决方案 > Laravel 雄辩的关系不起作用

问题描述

我有两个表usersnotifications,我的表中有一个外键,notification_idusersnotifications.blade.php,我试图让用户通过idnotifications

通知控制器:

public function notifications() {
    $notifications = App\Notification::latest('created_at')->get();
    return view('notifications', compact('notifications'));
}

通知.blade.php:

@foreach ($notifications as $notification)
    {{ $notification->user->id }}
@endforeach

用户.php(模型):

public function notifications() {
    return $this->hasMany('App\Notifications', 'notification_id');
}

Notification.php(模型):

public function user() {
    return $this->belongsTo('App\User', 'notification_id');
}

通知表架构:

Schema::create('notifications', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
});

用户表架构:

Schema::create('users', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
    $table->unsignedInteger('notification_id')->nullable();
    $table->foreign('notification_id')->references('id')->on('notifications');
});

但我正在尝试获取非对象错误的属性。

标签: phplaravelormforeign-keys

解决方案


外键必须在Notification模型(user_id)而不是User模型中。因为你的关系说

编辑:

你的代码必须是这样的: User.php(model):

public function notifications() {
  return $this->hasMany('App\Notification', 'user_id');
}

Notification.php(模型):

public function user() {
    return $this->belongsTo('App\User', 'user_id');
}

通知表架构:

Schema::create('notifications', function (Blueprint $table) {
    $table->engine = "InnoDB";
    $table->increments('id');
    $table->string('message');
    $table->timestamps();
    $table->unsignedInteger('user_id')->nullable();
    $table->foreign('user_id')->references('id')->on('user');
});

用户表架构:

Schema::create('users', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('email')->unique();
    $table->string('password');
});

推荐阅读