我有两个表,分别为users
和notifications
,并且在我的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');
});
但是我遇到试图获取非对象属性错误。
答案 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 所说的关系。