【问题标题】:How to get product name from pivot table using laravel?如何使用 laravel 从数据透视表中获取产品名称?
【发布时间】:2023-03-03 23:54:02
【问题描述】:

我正在尝试从数据透视表中获取产品名称,但不幸的是我不知道如何从数据透视表中获取产品名称,请帮助我,谢谢。

产品型号

 public function category()
    {
        return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id');
    }

产品类别模型

public function products()
    {
        return $this->belongsToMany('App\Product', 'product_category', 'mf_product_category_id', 'product_id');
    }

控制器

public function getproduct(Request $request)
    {
        // getting category Id
        $categoryId = $request->category;
        // getting product Id
        $name = trim($request->product);

        $productId = Product::where('name', $name)->pluck('id');

        $getProductcategory = ProductCategoryCount::whereIn('mf_product_category_id', $categoryId)->whereIn('product_id', $productId)->get();

        return $getProductcategory;
        // return response()->json($getproduct);
    }

【问题讨论】:

    标签: laravel


    【解决方案1】:

    laravel doc 中所述,您可以在关系上使用withPivot 检索数据透视表额外数据。

    产品模型

    中定义category
    public function category()
    {
        return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id')
            ->withPivot('Your_extra_data_on_pivot_table');
    }
    

    通过查询产品,你可以得到类别(我建议是categories)。你可以这样检索它$products->first()->pivot->{name of_your_extra_data_on_pivot_table}

    如果你eager load这个关系会更优化。

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多