gpt4 book ai didi

mysql - Eloquent - 多对多,用户主题按用户id删除所有主题

转载 作者:行者123 更新时间:2023-11-29 12:16:39 24 4
gpt4 key购买 nike

考虑到 Eloquent 多对多关系:

迁移:

class Topics extends Migration
{
public function up()
{
Schema::create('topics', function(Blueprint $table) {
$table->increments('id');
$table->string('name');
});

Schema::create('topic_user', function(Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('topic_id')->unsigned();
$table->foreign('topic_id')->references('id')->on('topics');
});
}
}

型号:

class User extends Model
{
public function topics()
{
return $this->belongsToMany('App\Topic', 'topic_user');
}
}

我想知道如何删除给定用户的所有主题,目前我的代码如下所示:

Auth::user()->topics()->delete();

但我遇到了异常:

ERROR: missing FROM-clause entry for table "topic_user" LINE 1: delete from "topics" where "topic_user"."user_id" = $1 ^ (SQL: delete from "topics" where "topic_user"."user_id" = 6)

我做错了什么?

最佳答案

这很简单:

Auth::user()->topics()->detach();

关于mysql - Eloquent - 多对多,用户主题按用户id删除所有主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29703137/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com