samedi 28 avril 2018

Model relationship creation uses the wrong field in Laravel

I want to create a new model using the relationship between a two model module and chapter and they have HasMany relationship between them as follow :

//Module mode
public function chapters()
{
    return $this->hasMany(Chapter::class, 'module_slug', 'slug');
}

//Chapters Model
public function module()
{
    return $this->belongsTo(Module::class, 'module_slug', 'slug');
}

And here's how I'm storing the models :

    $module = Module::create([
        'title' => $request->module_title,
        'icon' => $request->module_title
    ]);

    $module->chapters()->create([
        'pdf_url' => $path,
        'title' => $request->chapter_title
    ]);

The Issue :

The problem I got is that the $module->chapters()->create() is using the id not the slug which I'm specifying as the primary key like this :

//Module model
protected $primaryKey = 'slug';
protected $keyType = 'string';


//Chapters model
protected $primaryKey = 'slug';
protected $keyType = 'string';

I don't know why it uses the id field like this screenshot :

The issue



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire