【问题标题】:How can I pull products according to categories in Laravel如何根据 Laravel 中的类别拉取产品
【发布时间】:2019-03-02 06:38:23
【问题描述】:

我正在尝试使用 Laravel 关系根据类别获取产品。

类别名称存储在 terms 表和 products 表中,我添加了 term_id 列。

这是我的条款表

这是我的 product

这是我迄今为止在Term模型中所做的——

public function products(){

    return $this->hasMany('shopist\Models\Product');

}

在我的控制器中-

    public function products()
        {

            $pro = term::where('term_id',2)->first();
            $pro->products;

        }

但我没有得到任何结果。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    请按照以下方式更正您在 Term 模型中的关系-

    public function products()
    {
        return $this->hasMany('shopist\Models\Product', 'term_id', 'term_id'); // foreign key and local key should be defined
    }
    

    您必须在 relation 中定义外键和本地键,因为您没有遵循 laravel 推荐的主键列名称约定。

    所以有必要告诉方法需要使用哪些键作为关系。

    【讨论】:

      【解决方案2】:

      试试

      public function products()
              {
      
                  return Term::where('term_id',2)->first();
      
              }
      

      或者如果您有产品模型

      public function products()
          {
      
              return Product::where('term_id',2)->first();
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-08
        相关资源
        最近更新 更多