Search code examples
laraveleloquentforeign-key-relationshipone-to-one

save one to one relationship. foreign keys in both tables


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?


Solution

  • First your users table does not need a pet_id. Drop it. Then

    Users Model

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

    Pet Model

    public function user()
    {
        return $this->belongsTo('App\User');
    }
    

    Now create a new User

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

    Examples:

    $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()