保存一对一的关系.两个表中的外键

jam*_*ray 2 one-to-one foreign-key-relationship laravel eloquent

我有两张表如下:

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`)
);
Run Code Online (Sandbox Code Playgroud)

我的模型有下一个:

用户:

public function relatedPet() {
    return $this->hasOne("Pet", "pet_id");
}
Run Code Online (Sandbox Code Playgroud)

宠物:

public function relatedUser() {
    return $this->belongsTo("User", "user_id ");
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

cha*_*fdo 6

首先,您的用户表不需要pet_id.算了吧.然后

Users 模型

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

Pet 模型

public function user()
{
    return $this->belongsTo('App\User');
}
Run Code Online (Sandbox Code Playgroud)

现在创建一个新的 User

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

例子:

$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()
Run Code Online (Sandbox Code Playgroud)