Laravel 5.6中多态关联下产品收藏的增删查实现方法
嘿,我来帮你搞定Laravel 5.6里多态关联的产品收藏操作!看你已经把Product和Favorite的模型关联基础都搭好了,接下来直接上具体的增删查实现方法:
1. 添加收藏
首先建议你给User模型也补充上收藏关联,这样操作会更顺手:
// app/User.php public function favorites() { return $this->hasMany(Favorite::class); } // 还可以加一个专门关联收藏产品的方法,简化后续查询 public function favoritedProducts() { return $this->morphedByMany(Product::class, 'favoritable', 'favorites'); }
接下来在控制器里处理收藏请求(假设用户已通过Auth认证):
// 获取当前用户和目标产品 $user = auth()->user(); $product = Product::findOrFail($request->product_id); // 方式一:通过用户模型创建收藏 $user->favorites()->create([ 'favoritable_id' => $product->id, 'favoritable_type' => Product::class, ]); // 方式二:通过产品模型创建收藏 $product->favorites()->create(['user_id' => $user->id]);
小提示:为了避免用户重复收藏同一个产品,最好给favorites表加唯一索引,在迁移文件里添加:
$table->unique(['user_id', 'favoritable_id', 'favoritable_type']);
这样数据库层面会阻止重复插入,你也可以在控制器里先判断是否已收藏,再执行创建逻辑。
2. 删除收藏
删除收藏同样有两种常用方式,根据业务场景选择:
$user = auth()->user(); $product = Product::findOrFail($request->product_id); // 方式一:通过用户收藏关联删除指定产品的收藏 $user->favorites() ->where('favoritable_id', $product->id) ->where('favoritable_type', Product::class) ->delete(); // 方式二:通过产品收藏关联删除当前用户的收藏 $product->favorites() ->where('user_id', $user->id) ->delete();
3. 查询收藏
查询当前用户收藏的所有产品
如果之前给User模型加了favoritedProducts关联,直接查询非常简洁:
$favoritedProducts = auth()->user()->favoritedProducts()->get();
如果没加这个关联,也可以用基础关联查询:
$favoritedProducts = auth()->user()->favorites() ->where('favoritable_type', Product::class) ->get() ->pluck('favoritable'); // 通过morphTo关联获取Product实例
判断用户是否已收藏某个产品
$isFavorited = auth()->user()->favorites() ->where('favoritable_id', $product->id) ->where('favoritable_type', Product::class) ->exists(); // 用favoritedProducts关联的简化写法 $isFavorited = auth()->user()->favoritedProducts()->where('id', $product->id)->exists();
查询某个产品的所有收藏用户
先给Favorite模型补充用户关联:
// app/Favorite.php public function user() { return $this->belongsTo(User::class); }
然后查询:
$product = Product::findOrFail($product_id); $productFans = $product->favorites() ->with('user') // 预加载用户模型,避免N+1查询 ->get() ->pluck('user');
内容的提问来源于stack exchange,提问作者moses toh
相关产品推荐
相关产品推荐

