twenty7 twenty7 - 5 months ago 14
MySQL Question

Saving model with not nullable relationship

Consider the following two relations:

User:

CREATE TABLE user (
id INT NOT NULL,
social_provider_id INT NOT NULL,
CONSTRAINT `user_social_provider_id_fk` FOREIGN KEY (`social_provider_id`)
REFERENCES `social_provider` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
)


Social provider:

CREATE TABLE social_provider (
id INT NOT NULL,
name VARCHAR NOT NULL )


Eloquent models:

class User extends Model{
protected $table = 'user';
public function socialProvider(){
return $this->hasOne('/SocialProvider');
}
}


Now I want to create a new User object and save it:

$user = new User();
$socialProvider = SocialProvider::find(1);
$user->socialProvider()->save($socialProvider);
$user->save();


But I get this exception on the line where I assign the SocialProvder object

Call to undefined method Illuminate\Database\Query\Builder::save()


I tried to save the User object first and then assign the relationship, but obviously this is not possible because of the
NOT NULL
constraint in the definition of the
user
table.

My workaround at the moment is to assign the relationship this way:

$user->social_provider_id = $socialProvider->id;


But I would like to use Eloquent's features.
How can I save a new model with a not nullable relationship, without having to assign IDs by myself?

Solution:
Like @Panagiotis Koursaris suggested, the solution is to use
associate()
instead of
save()

Answer

Try this:

$user = new User();
$socialProvider = SocialProvider::find(1);
$user->socialProvider()->associate($socialProvider);
$user->save();