php - 使用数据透视表按类别 ID 获取产品

标签 php sql laravel eloquent laravel-relations

我有一个函数,我可以传递类别 ID,并基于该 ID 来获取所有产品。

这是我的数据库的结构

类别数据库:

category_name

产品数据库:

product_name;

类别产品:

category_id;
product_id;

下面是它们之间的关系

在产品中:

public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

所属类别:

public function products()
    {
        return $this->belongsToMany(Product::class);
    }

我测试了多个查询,但对我的情况没有任何作用。

最佳答案

您可以通过两种不同的方式来实现

验证类别是否存在的间接方式(2 个查询)

$category = Category::with('products')->findOrFail($categoryId);
// you can also do without the with(); only one id, so no benefit for the eager load
// $category = Category::findOrFail($categoryId);
$products = $category->products;

直接方式,如果类别不存在(但没有消息),将返回一个空集合(1个查询)

$products = Product::whereHas('categories', function($qbCategory) use($categoryId) {
    $qbCategory->where('id',$categoryId);
})->get();

关于php - 使用数据透视表按类别 ID 获取产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68015883/

相关文章:

php - 如何在wordpress选项中保存短代码的内容?

php - 在 "background"运行函数

mysql - [My]需要foreach处理的SQL查询语法

laravel - 表单提交到错误的网址。如何对我的网站进行表单操作

apache - Laravel 使用 Mod_rewrite 强制 HTTPS

php - 为什么mysql查询需要很长时间才能收到结果?

php - 添加到不同表时删除一行

sql - 总结sql server 2008中的一些xml节点值

mysql - mysql 是否具有 Oracle 的 "analytic functions"的等效项?

php - Laravel - 未按要求设置 session 存储