php - Laravel 雄辩的关系不起作用
问题描述
我有两个表users
和notifications
,我的表中有一个外键,notification_id
在users
中notifications.blade.php
,我试图让用户通过id
表notifications
:
通知控制器:
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');
});
但我正在尝试获取非对象错误的属性。
解决方案
外键必须在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');
});
推荐阅读
- javascript - JavaScript 函数的返回值错误
- macos - 如何从 SwiftUI 视图中运行 AppleScript?
- django - 如何在 django 模板中转换列表中的字段?
- android - 如何获取房间数据库大小
- excel - 如何将 Excel 事件处理程序应用于所有工作表?
- python - 访问数组列表的元素
- flutter - Flutter:在凸起按钮中带有参数的函数
- php - 连接到我的 Wordpress MySQL 数据库的问题
- ios - 当我在 xcode 中切换到第二页时出现问题(swift)
- unity3d - Unity:.car 文件格式?