I have two tables as follow:
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`)
);
And my models have the next:
USERS:
public function relatedPet() {
return $this->hasOne("Pet", "pet_id");
}
PETS:
public function relatedUser() {
return $this->belongsTo("User", "user_id ");
}
I want to save an User and relate to an existent pet, but i don't know how to do that:
$user= new User(array("any_data"=>"Hi, this is a test"));
$pet = Pet::find(1);
How can I create the relation between the two objets?
First your users table does not need a
pet_id
. Drop it. ThenUsers
ModelPet
ModelNow create a new
User
Examples: