【问题标题】:How to write Laravel One to One relationship model and migration如何编写 Laravel 一对一关系模型和迁移
【发布时间】:2020-09-19 06:29:51
【问题描述】:

对于一对一关系,每个user 应该只有一个phone 条目。

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


【解决方案1】:

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) 我应该在手机迁移中的user_id 列中添加unique 约束吗?
** 是的,你可以。但是,正如我在第二点中建议的那样,只需在 users 表中添加一个 phone 列(如果您愿意,否则这也可以)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 1970-01-01
    • 2021-12-27
    • 2018-09-27
    • 1970-01-01
    • 2016-08-25
    • 2019-03-31
    • 2012-01-25
    相关资源
    最近更新 更多