Laravel雄辩的关系不起作用

时间:2019-03-22 15:55:30

标签: php laravel orm foreign-keys

我有两个表,分别为usersnotifications,并且在我的notification_id表中有一个users外键,在notifications.blade.php中,我正在尝试通过id表的notifications吸引用户,例如:

NotificationController:

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

notifications.blade.php:

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

User.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');
});

但是我遇到试图获取非对象属性错误。

2 个答案:

答案 0 :(得分:1)

外键必须采用Notification模型(user_id)而非User模型。 因为你的亲戚这么说

编辑:

您的代码必须是这样的: User.php(模型):

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');
});

Users表架构:

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

答案 1 :(得分:0)

我已解决此问题,感谢 Chris Forrence ,我已更改了 Chris Forrence 所说的关系。