laravel - 如何通过多对多关系获取与同一张表相关的行 - Laravel
问题描述
我有一个名为 Products 的模型,我需要将相关产品返回到视图中。所以我创建了另一个模型,叫做 Category,关系是多对多的。
我设法获得了相关产品,但每个产品都附有一个不太好的类别,这是我的代码:
$categories = Product::find($id)->categories;
$products = new Product;
$products = $products->toArray();
foreach ($categories as $cat) {
array_push($products, Category::find($cat->id)->products);
}
return $products;
有更好的方法吗?
解决方案
我使用常规 SQL 查询完成了它,这是希望帮助某人的代码
$catIDs = DB::table('product_category')
->select('category_id')
->where('product_id', $id)
->pluck('category_id');
$productsIDs = DB::table('products')
->select('product_category.product_id')
->distinct()
->rightJoin('product_category', 'products.id', '=', 'product_category.product_id')
->whereIn('category_id', $catIDs)
->pluck('product_id');
$relatedProducts = Product::with('firstImage')
->whereIn('id', $productsIDs)
->where('id', '!=', $id)
->inRandomOrder()
->get();
推荐阅读
- performance - Arduino:检测两个信号是否在 100 微秒内发生变化
- json - 如何将 JSON 文件(包含测试执行结果)从我的本地系统传输到 azure VM (Linux) 或连接到网络服务器的存储磁盘。
- php - 超过 100 万用户的 Laravel 记分牌
- javascript - 上传图片提交
- python - Keras 预训练 VGG19 模型的层输出为相同的输入产生不同的输出
- ruby-on-rails - Ruby on rails 协会 - 用户(设计)在注册和登录后可以“创建团队”或“加入团队”
- c# - C#获取集合中最流行的2项组合
- javascript - 按键删除项目,Firebase React Native
- java - Gradle Heroku 任务“阶段”
- javascript - 使用 javascript 编写 css 属性无法正常工作