模型关系创建使用Laravel中的错误字段

时间:2018-04-29 01:02:45

标签: laravel laravel-5 eloquent

我想使用两个模型modulechapter之间的关系创建一个新模型,它们之间有HasMany个关系,如下所示:

//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');
}

以下是我存储模型的方式:

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

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

问题:

我遇到的问题是$module->chapters()->create()正在使用id而不是slug我正在指定为主键,如下所示:< / p>

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


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

我不知道它为什么使用id字段,如此截图:

The issue

1 个答案:

答案 0 :(得分:1)

将此添加到您的模型中:

public $incrementing = false;