Eloquent - 多对多,users-topics 删除所有用户id的主题
Eloquent - Many To Many, users-topics delete all topics by user id
给定 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" = ^ (SQL: delete from
"topics" where "topic_user"."user_id" = 6)
我做错了什么?
这很简单:
Auth::user()->topics()->detach();
给定 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" = ^ (SQL: delete from "topics" where "topic_user"."user_id" = 6)
我做错了什么?
这很简单:
Auth::user()->topics()->detach();