jeudi 8 décembre 2016

Laravel Failed to save morphToMany relationship

Here is my code:

// Table Structure
users
    id - integer
    name - string
    ...

countries
    id - integer
    name - string

localizations
    country_id - integer
    localizationable_id- integer
    localizationable_type - string

//User.php

public function localizations()
{
    return $this->morphToMany(Country::class, 'localizationable', 'localizations');
}


// Country.php

 public function users()
{
    return $this->morphedByMany(User::class, 'localizationable', 'localizations');
}

// Save

$user = User::find(1);
$localization = new Localization();
$localization->country_id = 1;

$user->localizations()->save($localization);

When saving I got this error SQLSTATE[HY000]: General error: 1364 Field 'localizationable_id' doesn't have a default value.

As far as I know Laravel will automatically put localizationable_id and localizationable_type

Any solution ?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire