【问题标题】:How to get category wise all product without one specific product ID in laravel?如何在 laravel 中获得没有一个特定产品 ID 的所有产品类别?
【发布时间】:2021-08-12 12:31:49
【问题描述】:

我有一个类别表,产品表。我想显示类别明智的所有产品,除了来自请求的一个特定产品 ID

这里是模型关系

产品型号

public function category(){
   return $this>belongsTo(Category::class);
}

类别模型

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

我通过这种方式获得所有产品

    $product = Product::findOrFail(10);
    $category_products = $product ->category->products;

但我想获得除 product_id 10 之外的所有产品。我怎样才能获得它?

【问题讨论】:

  • 类别和产品之间是否存在多对多关系?数据透视表的目的是什么?如果存在 m:m 关系,那么如果产品 10 属于多个类别并且这些类别可能共享重复的产品怎么办?你能发布你的模型定义吗
  • 我已经编辑了我的帖子,请再次检查,这里没有数据透视表

标签: php mysql laravel eloquent


【解决方案1】:

要显示类别明智的产品并从相关集合中排除特定产品,您可以使用 with 查询产品类别并急切加载相关产品,但使用关闭方法从集合中删除您想要的产品

$product = 10;
$category = Category::with(['products'=> function($query) use($product)  {
                $query->where('id','!=', $prodcut);
            }])
            ->whereHas('products', function (Builder $query) use($product) {
                $query->where('id', $product);
            })->get();

【讨论】:

    【解决方案2】:

    您可以使用with() 方法约束急切关系,并传递一个闭包。

    $id = 10;
    
    $product = Product::findOrFail($id)
        ->with(['category.products' => fn ($query) => $query->where('id', '!=', $id)])
        ->get();
    
    $otherProducts = $product->category->products;
    

    php 7.4 之前的版本

    $product = Product::findOrFail($id)
        ->with(['category.products' => function ($query) use ($id) {
            return $query->where('id', '!=', $id);
        }])
        ->get();
    

    再想一想,更有效的方法可能是直接查询 products 表:

    $otherProducts = Product::query()
        ->where('category_id', $categoryId)
        ->where('id', '!=', $productId)
        ->get();
    

    【讨论】:

    • 您的代码给出了错误“语法错误,意外'=>' (T_DOUBLE_ARROW),期望']'”
    • 啊,那么你可能使用的是旧的 php 版本?我在版本中添加了 pre 7.4 语法
    • 我从你的 7.4 之前的语法代码中一无所获
    • 我做了几处编辑,但请注意,这个网站最好是有人为您指明正确的方向,而不是逐字写出您的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多