为一篇文章添加多个类别:
public static function setCategory(Request $request) {
$article = Article::where('id', $request->article_id)->first();
$categories_ids = json_decode($request->categories_ids);
$article->categories()->attach($categories_ids);
}
假设输入数组[1,2,3,4],其中4是一个不存在的类别。如何确保添加了所有现有的类别,而忽略了4个类别?
如果你想用一种优雅的方式来做,我会这样做:
$article = Article::findOrFail($request->article_id);
$requestedCategoriesIds = json_decode($request->categories_ids);
$keyName = (new Category())->getKeyName();
$existingCategoriesIds = Category
::whereKey($requestedCategoriesIds)
->pluck($keyName);
$article->categories()->attach($existingCategoriesIds);