skip to Main Content

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;

2

Answers


  1. 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->title = 'Some Title';
    $article->save();
    
    $article->sections()->sync([4,6,5]);
    
    Login or Signup to reply.
  2. 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');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search