首页 > 解决方案 > 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();
    });
}

标签: mysqllaravel

解决方案


在 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 设法获取关系信息的方式。

另外,检查这个答案


推荐阅读