如何编写Laravel一对一关系模型和迁移

时间:2020-06-01 00:24:10

标签: laravel relationship one-to-one

在一对一关系中,每个phone只能有一个user条目。

  1. 那么,为什么我可以添加多个电话号码?
  2. 这是否意味着App\User::find(1)->phone仅返回数据库中找到的第一个电话?
  3. 我应该在电话迁移的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');
});

1 个答案:

答案 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约束吗?
** ,可以。但是,正如我在第二点建议的那样,只需在用户表中有一个电话栏(如果您愿意,否则也可以)