【发布时间】:2020-09-19 06:29:51
【问题描述】:
对于一对一关系,每个user 应该只有一个phone 条目。
- 那么,为什么我可以添加多个电话号码?
- 这是否意味着
App\User::find(1)->phone只返回在数据库中找到的第一部电话? - 我是否应该在手机迁移的
user_id列中添加unique约束?
用户模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the phone record associated with the user.
*/
public function phone()
{
return $this->hasOne('App\Phone');
}
}
手机型号
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
用户表迁移:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
手机迁移:
Schema::create('phones', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('phone');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
【问题讨论】:
-
是的,您应该添加一个
unique约束,如answer 中所述。
标签: laravel relationship one-to-one