Laravel与MySQL关系外键未出现

时间:2018-06-24 02:04:53

标签: mysql laravel

我只想问一下,在Laravel中,每次我使用外键约束时,约束图标键未显示在 MYSQL 内是否正常?另外,内部索引未显示。

注意:这只是为了澄清我是否做错了方法。请帮忙修改。谢谢。

这是图片

enter image description here

架构:

public function up()
{
    Schema::create('subjects', function (Blueprint $table) {
        $table->increments('id');
        $table->string('subject_name');
        $table->integer('Level_id')->unsigned()->nullable();
        $table->timestamps();
    });
}

2 个答案:

答案 0 :(得分:1)

From the documentation:

  

Laravel还支持创建外键约束,   用于在数据库级别强制引用完整性。   例如,让我们在posts表上定义一个user_id列,   引用用户表上的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

答案 1 :(得分:0)

在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。我们可以   在雄辩中定义此关系:

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