我只想问一下,在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();
});
}
答案 0 :(得分:1)
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_id
与users
的关系:$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。