代码之家  ›  专栏  ›  技术社区  ›  DevonDahon

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

  •  0
  • DevonDahon  · 技术社区  · 6 年前

    一对一的关系,我应该只有一个 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 回复  |  直到 6 年前
        1
  •  0
  •   Digvijay    6 年前

    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) 这是否意味着应用程序\用户::查找(1)->phone仅返回数据库中找到的第一个电话?
    **只要你的亲戚 哈松 ,您获取的数据将是user\u id=当前用户的数据。如果您计划在整个项目中为每个用户提供一个电话号码,那么 我可以建议你 只需将电话号码列添加到用户表中。


    3) 我应该添加 unique 约束到 user_id 电话迁移中的列?
    ** 对 ,您可以。然而,正如我在第二点中所建议的,只需在users表中有一个phone列(如果愿意,否则也可以)