Emjey23
Emjey23

Reputation: 367

Eloquent Update with One-to-One relationship

I am want to update my records in my database using Eloquent model. I am having an error in updating user_profile table that saying where id is not null.

User Model

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('App\Models\Common\UserProfile');
    }
}

UserProfile Model

class UserProfile extends Model
{
    public function user()
    {
        return $this->belongsTo('\App\Models\User');
    }
}

Controller

$user->fill($data);
$user->save();
$user->profile->fill($data);
$user->profile->save();

In MySQL query it looks like this:

UPDATE users, user_profiles
SET users.name='Test Name',
user_profiles.email='[email protected]'
WHERE users.id=1
 AND user_profiles.user_id=1;

I know MySQL query but I'm new to Eloquent and I want to do it in Eloquent model. Maybe there are some in here that can provide an explanation on how the magic works in Eloquent.

Upvotes: 0

Views: 521

Answers (1)

Paul Spiegel
Paul Spiegel

Reputation: 31832

By default eloquent assumes, that any model has an id column as primary key. If that is not the case, you need to "register" the primary key with

protected $primaryKey = 'user_id';

in the model class.

Upvotes: 1

Related Questions