在一对一关系中,每个phone
只能有一个user
条目。
App\User::find(1)->phone
仅返回数据库中找到的第一个电话?unique
列中添加user_id
约束吗?用户模型:
<?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');
});
答案 0 :(得分:0)
1)那么,为什么我可以添加多个电话号码?
**在向数据库添加电话号码时,只需搜索当前用户是否有电话号码即可。如果是,则对其进行更新。否则,创建一个新的。选中updateOrCreate
// If there is a user with id 2 then SET the phone to 7897897890.
// If no user with id 2 found, then CREATE one with user_id 2 and phone number to 7897897890
Phone::updateOrCreate(
['user_id' => 2],
['phone' => '7897897890']
);
2)这是否意味着App \ User :: find(1)-> phone仅返回数据库中找到的第一个电话?
**只要您的关系为 hasOne ,您提取的数据即为其中user_id =当前用户的数据。如果您计划在整个项目中为每个用户提供一个电话号码,那么我建议可以将电话号码列简单地添加到用户表中。
3)我应该在电话迁移的unique
列中添加user_id
约束吗?
** 是,可以。但是,正如我在第二点建议的那样,只需在用户表中有一个电话栏(如果您愿意,否则也可以)