Laravel 在事务模式下保存数据透视表 table 时出错

Laravel error on save pivot table in transaction mode

我正在尝试通过创建模型实例在交易期间创建新记录,然后装饰所有属性。

Post 型号

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function authors()
{
    return $this->belongsToMany(
       User::class, 'blog_post_authors', 'post_id', 'author_id'
    );
}

保存模式

// start transaction mode
DB::beginTransaction();

$postModel = new Post(
    ['title' => 'Hello world!']
);

// relate authors
$postModel->authors()->attach(7);

\DB::commit();

但是,它甚至在提交事务之前就抛出异常。

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `blog_post_authors` (`author_id`, `post_id`) values (7, ?))

你应该保存 Post 模型,也许你错过了:

DB::beginTransaction();

$postModel = new Post(
    ['title' => 'Hello world!']
);
$postModel->save();

// relate authors
$postModel->authors()->attach(7);

\DB::commit(); 

您正在创建 $postModel,因为它是在 php 中创建的,但尚未保存到数据库中,因此还没有 id,因为id 它可能是一个由数据库确定的自动递增值。

所以首先保存你的 postModel,然后应用作者关系。

要么: $postModel = Post::create([...]); 或添加: $postModel->save();