【问题标题】:Laravel with MySQL relationship foreign key not appearingLaravel与MySQL关系外键没有出现
【发布时间】:2018-06-24 11:39:13
【问题描述】:

我只是想问一下,在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();
    });
}

【问题讨论】:

  • 你是如何指定外键约束的?
  • 你能分享那个表的迁移文件吗?
  • 我已经用架构更新了我的问题
  • @Grace 你没有在迁移中定义外键
  • @Grace 我没有看到任何限制。但我认为问题是什么。

标签: mysql laravel


【解决方案1】:

当你在 Laravel 中定义 Relationship 时,像这样:

class Comment extends Model
{
    /**
     * Get the original post from where the comment is from.
     */
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

默认情况下,Laravel 不会在您的数据库中定义关系约束。这不是 Laravel 处理关系的方式。

要指定一个,需要在迁移中添加约束,比如documentation states

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 根据模型名称假定关系的外键。在这种情况下,电话模型假定使用 user_id 外键。

如你所见,这是 Laravel 设法获取关系信息的方式。

另外,请查看answer

【讨论】:

  • 感谢现在约束也出现了索引感谢人.. 但顺便说一句,为什么使用我以前的代码我仍然可以设法保存数据 laravel 允许它?
【解决方案2】:

From the documentation:

Laravel 还支持创建外键约束, 它们用于在数据库级别强制引用完整性。 例如,让我们在 posts 表上定义一个 user_id 列 引用 users 表上的 id 列:

使用默认users 表和新posts 表的示例,已定义:

Schema::table('posts', function (Blueprint $table) {
    $table->unsignedInteger('user_id');

    $table->foreign('user_id')->references('id')->on('users');
});

由此可以看出$table->unsignedInteger('user_id');是表posts中列的定义,

然后,我们需要定义user_idusers的关系:$table->foreign('user_id')->references('id')->on('users');定义了re

【讨论】:

    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2021-10-29
    • 2020-08-13
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多