如何删除用户类别?

How to delete categories of user?

我尝试删除如下用户类别:

Category::with('user', Auth::user()->id)->where("user_id", $id)->delete();

类别模型有关系:

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'id');
}

但对我不起作用

User model:

public function categories()
    {
        return $this->belongsToMany('App\Category');
    }

试试不用 with():

Category::where("user_id", $id)->delete();

Update 用户模型代码添加后:

belongsToMany 关系的逆关系是另一个 belongsToManybelongsTo 关系的逆关系是 hasManyhasOne

您必须决定您想要的用户和类别之间的关系,因为 belongsTo 不适用于反向 belongsToMany

根据您在回答和评论中所写的内容,您似乎想要多对多关系(您有一个中间 table),在这种情况下您必须使用 belongsToMany 在两个模型中,然后您可以使用此代码删除用户类别分配:

$user->categories()->detach()

我认为你需要充实它们之间的关系。现在,根据您的关系代码,类别 table 中应该有一个 user_id

类别模型上的关系应该是这样的:

public function users()
{
    return $this->belongsToMany(User::class);
}

并且您需要一个名为 category_user 的 table 才能建立关系。下面是迁移的示例:

Schema::create('category_user', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('category_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();

    $table->foreign('category_id')->references('id')->on('categories');
    $table->foreign('user_id')->references('id')->on('users');
})

然后您就可以通过以下方式将用户添加到类别中:

$category->users()->attach(Auth::id());
Auth::user()->categories()->attach([ 1, 2, 3 ... ]);

并删除:

$category->users()->detach(Auth::id());
Auth::user()->categories()->detach([ 1, 2, 3 ... ]);

您还可以使用 sync,它将分离任何不在您的数组中的元素并附加任何当前未附加的元素:

Auth::user()->categories()->sync([ 1, 2, 3, ... ]);