Laravel 保存一对一关系。两个表中的外键
我有两张表格如下:Laravel 保存一对一关系。两个表中的外键,laravel,eloquent,foreign-key-relationship,one-to-one,Laravel,Eloquent,Foreign Key Relationship,One To One,我有两张表格如下: 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_IN
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 ");
}
宠物:
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);
如何创建两个对象之间的关系?首先,您的用户表不需要
宠物id
。放下它。然后
用户
型号
public function pet()
{
return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne
}
public function user()
{
return $this->belongsTo('App\User');
}
Pet
型号
public function pet()
{
return $this->hasOne('App\Pet'); // Changed form hasMany to hasOne
}
public function user()
{
return $this->belongsTo('App\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,因为我需要从用户对象获取pet,还需要更新pet对象中的用户。很抱歉。我明白了,把hasMany改成hasOne。但是我需要pet_id,因为我需要从用户对象获取pet,也需要从pet对象获取用户。我错了?你可以通过
$user->pet
从用户对象获取宠物。不需要用户表上的宠物id。我可以从宠物对象获取用户吗?