Reputation: 166
I have users
and phone
table and I made one-to-one relationship in laravel, that's working perfectly but if I try to add data (foreign key user_id) manually to phone table without reference of any user(id), it also work.
In mysql(phpmyadmin), there is no foreign key relation built after the migration.
So I want to ask, what are the advantages of foreign key if it does't put any constraints in db tables or if is there any way to add these constraints using laravel, kindly let me know.
Code snippets
app/Phone.php
public function user(){
return $this->belongsTo('App\User');
}
app/User.php
public function phone(){
return $this->hasOne('App\Phone');
}
routes/web.php
Route::get('/', function () {
$user = factory(\App\User::class)->create();
$phone=new \App\Phone;
$phone->phone = '123456789';
$phone->user_id = '1';
$user->phone()->save($phone);
});
Phone (migration)
public function up()
{
Schema::create('phones', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('phone');
$table->unsignedBigInteger('user_id')->index();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
Users table does not have any user with id 10 but this also works and add data to phone (user_id)
$phone->phone = '123456789';
$phone->user_id = '10';
$phone->save();
Upvotes: 3
Views: 319
Reputation: 291
Without the foreign key, there is no point to use a relational database. It helps you to maintain integrity and consistency. It will always check the records in the parent table while inserting into child table, on another hand, it reduces the execution time because of indexes.
In your case, you are able to insert the data into the child table because you did not make the reference key constraints. If you are not using that then you are breaking the role of relational database engines.
It's not a part of any framework or programming language, it's all about right database configuration and design. Laravel is not responsible for it.
There is a disadvantage too but it's only on the machine. It increases the cost of the server CPU.
Upvotes: 0