【问题标题】:save one to one relationship. foreign keys in both tables保存一对一的关系。两个表中的外键
【发布时间】:2015-08-26 00:43:42
【问题描述】:

我有两张表如下:

CREATE TABLE pets(
      id int NOT NULL AUTO_INCREMENT,
          user_id int,
          any_data varchar(255),
      foreign key (user_id) references users(id),
      primary key(`id`)
);

CREATE TABLE users(
      id int NOT NULL AUTO_INCREMENT,
          pet_id int,
          any_data varchar(255),
      foreign key (pet_id) references pets(id),
      primary key(`id`)
);

我的模型还有下一个:

用户:

public function relatedPet() {
    return $this->hasOne("Pet", "pet_id");
}

宠物:

public function relatedUser() {
    return $this->belongsTo("User", "user_id ");
}

我想保存一个用户并与现有的宠物相关联,但我不知道该怎么做:

$user= new User(array("any_data"=>"Hi, this is a test"));
$pet = Pet::find(1);

如何创建两个对象之间的关系?

【问题讨论】:

    标签: laravel eloquent foreign-key-relationship one-to-one


    【解决方案1】:

    首先,您的用户表不需要pet_id。算了吧。那么

    Users模特

    public function pet()
    {
        return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne
    }
    

    Pet模特

    public function user()
    {
        return $this->belongsTo('App\User');
    }
    

    现在创建一个新的User

    $user = \App\User::create($data); // You need to set $fillable property
    $pet = \App\Pet::findOrfail($id)
    $pet->user()->associate($user);
    $pet->save();
    

    例子:

    $user = \App\User::findOrFail($id);
    $pet = $user->pet
    
    // Inserting a new user and a pet
    $anotherUser = \App\User::create($data);
    $anotherPet = new \App\Pet($data);
    $anotherUser->pet()->save($anotherPet);
    
    $pet = \App\Pet::findOrFail($id);
    $user = $pet->user
    
    // Inserting a new pet, a user and then associating them
    $anotherPet = \App\Pet::create($data);
    $anotherUser = \App\User::create($data);
    $anotherPet->user()->associate($anotherUser);
    $anotherPet->save()
    

    【讨论】:

    • 我想要一对一的关系(如标题所示),而不是一对多。我需要 pet_id 因为我需要从用户对象中获取宠物,也需要从宠物对象中获取用户
    • 已更新。对于那个很抱歉。将hasMany 更改为hasOne
    • 我明白了。但我需要 pet_id 因为我需要从用户对象中获取宠物,也需要从宠物对象中获取用户。我错了吗?
    • 您可以通过$user->pet从用户对象中获取宠物。不需要 users 表上的 pet_id。
    • 我可以从宠物对象中获取用户吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多