Home > front end >  laravel can't find the id of main model in many-to-many realtionship
laravel can't find the id of main model in many-to-many realtionship

Time:12-27

I'm using the attach to create many to many relationship.

Article model:

class Article extends Model
{
public function sections()
    {
        return $this->belongsToMany(Section::class);
    }
}

Section Model:

class Section extends Model
{
    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }
}

attaching sections to the article

$sections = [4,6,5];
$article->sections()->attach($sections);

the error i'm getting

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'article_id' cannot be null

INSERT INTO `article_section` (`article_id`, `section_id`) VALUES (?, 5), (?, 6), (?, 7)

I tried to switch between attach, detach, and sync\ sync only accepted the first element from the array and returned the same error with this SQL

INSERT INTO `article_section` (`article_id`, `section_id`) VALUES (?, 5), (?, 6), (?, 7)

detach returned false;

CodePudding user response:

If you are on the store method:

$article = new Article;
$article->title = 'Some Title';
$article->save();

$article->sections()->sync([4,6,5]);

And if you are on the update method:

$article = Article::find(1);

$article->sections()->sync([4,6,5]);

CodePudding user response:

YOU need to add the pivot table name to the belongsToMany relations and the foreign ids in the table

class Article extends Model
{
public function sections()
    {
        return $this->belongsToMany(Section::class,'table_name');
    }
}


class Section extends Model
{
    public function articles()
    {
        return $this->belongsToMany(Article::class,'table_name');
    }
}
  • Related