mysql - Laravel与MySQL关系外键没有出现
问题描述
我只是想问一下,在 Laravel 中,每次我使用外键约束时,约束图标键都没有显示在MYSQL中是否正常?此外,内部索引未显示。
注意:这只是为了澄清我是否以错误的方式做事。请帮忙修改。谢谢。
这是图像
架构:
public function up()
{
Schema::create('subjects', function (Blueprint $table) {
$table->increments('id');
$table->string('subject_name');
$table->integer('Level_id')->unsigned()->nullable();
$table->timestamps();
});
}
解决方案
在 Laravel 中定义关系时,如下所示:
class Comment extends Model
{
/**
* Get the original post from where the comment is from.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Laravel 默认没有在你的数据库中定义关系约束。这不是 Laravel 处理关系的方式。
要指定一个,您需要在迁移中添加约束,如文档所述:
Schema::table('comments', function (Blueprint $table) {
$table->unsignedInteger('post_id');
// Check this part:
$table->foreign('post_id')->references('id')->on('posts');
});
更新:
我认为文档的实际版本(L5.6)已经删除了这部分,但在L5.0中你可以看到它:
检查这部分:
让我们想象一个
User
模型可能有一个Phone
. 我们可以在 Eloquent 中定义这种关系:class User extends Model { public function phone() { return $this->hasOne('App\Phone'); } }
传递给该
hasOne
方法的第一个参数是相关模型的名称。一旦定义了关系,我们就可以使用 Eloquent 的动态属性来检索它:$phone = User::find(1)->phone;
该语句执行的 SQL 如下:
select * from users where id = 1 select * from phones where user_id = 1
请注意,Eloquent 根据模型名称假定关系的外键。在这种情况下,Phone 模型假定使用 user_id 外键。
正如你在粗体中看到的,这就是 Laravel 设法获取关系信息的方式。
另外,检查这个答案。
推荐阅读
- excel - 查找与特定日期最接近的日期
- spring-boot - 在 User-Agent 中获取多个浏览器详细信息
- openid - 在 keycloak 中添加我的应用程序作为身份提供者
- python - 作为服务的 TensorFlow 模型给出了错误
- c# - 程序写入 WPF 文本框时如何降低高 CPU 使用率?
- neo4j - windows下Gremlin-neo4j的安装和配置
- arrays - 按键合并多个数组 - Angular 5,Typescript
- php - Yii2-无法将模型从控制器传递到视图
- flask - Flask 不安分的预处理器“DELETE_RESOURCE”没有被调用
- javascript - 如何在数据库中存储数据 onclick 按钮?