Home > OS >  Laravel 8 eloquent missing 1 field while creating a sql query
Laravel 8 eloquent missing 1 field while creating a sql query

Time:11-12

I got a problem with eloquent, I have a controller with such a code

$pivot = MovieGenre::where('movie_id', $id)->delete();
        if($request->input('genres')){
            foreach ($request->input('genres') as $genre) {
                $pivot = MovieGenre::create([
                    'movie_id' => $id,
                    'genre_id' => $genre,
                ]);
            }
        }

and for example 2 more same pivots that's working, that pivots are same and controller made same way while I'm trying to use it I got an error enter image description here

This query missing 'genre_id' in the query but I gave this field in method CREATE from pivot model. Model file is empty. just 'extends Pivot'

CodePudding user response:

You are not using the relationship from a Movie model to Genre model here. You are directly interacting with a pivot table (which would just be a regular Model at this point, not a custom pivot).

You can simplify all of this if you used the relationship from Movie to Genre:

class Movie extends Model
{
    public function genres()
    {
        // convention would name the table genre_movie
        return $this->belongsToMany(Genre::class, 'movie_genre')->withTimestamps();
    }
}

Movie::findOrFail($id)->genres()->sync((array) $request->input('genres'));

Laravel 8.x Docs - Eloquent - Relationships - Many to Many - Retrieving Intermediate Table Columns withTimestamps

Laravel 8.x Docs - Eloquent - Relationships - Inserting & Updating Related Models - Many to Many - Syncing Associations sync

If you don't want to use the relationships then make MovieGenre a regular Model and set those fields as fillable:

class MovieGenre extends Model
{
    protected $fillable = [
        'movie_id',
        'genre_id',
    ];
}
  • Related