我有两张表如下:
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");
}
PETS:
public function relatedUser() {
return $this->belongsTo("User", "user_id ");
}
我想保存用户并与现有宠物有关,但我不知道该怎么做:
$user= new User(array("any_data"=>"Hi, this is a test"));
$pet = Pet::find(1);
如何创建两个对象之间的关系?
答案 0 :(得分:6)
首先,您的用户表不需要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()