You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel模型关联字段错误:Module与Chapter关联创建问题

Hey there! Let's work through your Laravel model relationship issue. From what you shared, you're setting up a HasMany/BelongsTo link between Module and Chapter using slugs instead of default primary keys, but you're hitting field errors when saving records. Let's break this down and fix it step by step.

First, Let's Confirm the Basics

Before diving into code, double-check these foundational pieces:

  • Database Table Structure: Make sure your chapters table has a module_slug field, and its data type matches the slug field in your modules table (e.g., both VARCHAR(255)). Adding a foreign key constraint here is optional but recommended for data integrity.
  • Fillable Fields: Both models need to have the relevant fields in their $fillable arrays to allow mass assignment.

Fix the Model Setup

Update your models to include the necessary fillable fields and verify the relationship definitions (yours look correct, but let's pair them with fillables):

// Module model
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Module extends Model
{
    // Allow mass assignment for these fields
    protected $fillable = ['title', 'icon', 'slug'];

    public function chapters() {
        // HasMany(related model, foreign key on chapters, local key on modules)
        return $this->hasMany(Chapter::class, 'module_slug', 'slug');
    }

    // Optional: Auto-generate slug if you don't pass it manually
    protected static function booted()
    {
        static::creating(function ($module) {
            $module->slug = Str::slug($module->title);
        });
    }
}
// Chapter model
use Illuminate\Database\Eloquent\Model;

class Chapter extends Model
{
    // Add module_slug to fillable so it can be mass-assigned
    protected $fillable = ['title', 'module_slug']; // Add other chapter fields here

    public function module() {
        // BelongsTo(related model, foreign key on chapters, owner key on modules)
        return $this->belongsTo(Module::class, 'module_slug', 'slug');
    }
}

Correct Ways to Save Associated Records

How you save your models will depend on your workflow—here are the two most common scenarios:

1. Create a Module first, then attach Chapters to it

This is the cleanest approach because the relationship will automatically populate the module_slug field for you:

// Create the Module (slug auto-generated if you added the booted() method above)
$module = Module::create([
    'title' => $request->module_title,
    'icon' => $request->icon
]);

// Create a Chapter directly linked to the Module
$module->chapters()->create([
    'title' => $request->chapter_title,
    // Add other chapter fields here—no need to manually set module_slug!
]);

2. Create a Chapter and link it to an existing Module

If you're creating a Chapter separately, make sure you pass the correct module_slug value:

// Fetch the existing Module (using its slug or title)
$module = Module::where('slug', $request->module_slug)->first();

// Create the Chapter with the module_slug explicitly set
Chapter::create([
    'title' => $request->chapter_title,
    'module_slug' => $module->slug, // Use the Module's slug, not its ID!
    // Add other chapter fields here
]);

Troubleshooting Common Errors

  • "Column not found: module_slug": You forgot to add the module_slug field to your chapters table. Generate a migration to add it:
    Schema::table('chapters', function (Blueprint $table) {
        $table->string('module_slug');
        // Optional: Add foreign key constraint
        $table->foreign('module_slug')->references('slug')->on('modules')->onDelete('cascade');
    });
    
  • "MassAssignmentException": The field (either slug on Module or module_slug on Chapter) isn't in the model's $fillable array—fix that as shown above.
  • Associated records don't show up: Double-check that the module_slug value in chapters exactly matches the slug value in modules (no typos, case mismatches, or extra spaces).

内容的提问来源于stack exchange,提问作者Rahmani Seif El Moulouk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:26:24