保存一对一的关系。两个表中的外键
save one to one relationship. foreign keys in both tables
我有如下两个表:
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);
如何创建两个对象之间的关系?
首先您的用户 table 不需要 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()
我有如下两个表:
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);
如何创建两个对象之间的关系?
首先您的用户 table 不需要 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()