【问题标题】:I am trying to query two tables in my laravel database我正在尝试在我的 laravel 数据库中查询两个表
【发布时间】:2021-05-27 14:53:06
【问题描述】:

我正在尝试查询数据库中的两个表,但它返回此错误。 我正在尝试通过多个表实现搜索。该项目是一个在线商店,有 3 个不同的表格,产品、类别和品牌。我只能搜索 Products 表,但似乎无法从我的刀片文件中获取相同的搜索字段来搜索类别或品牌并返回相关产品的结果。

QLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous (SQL: select * from `categories` inner join `products` on `products`.`category_id` = `categories`.`id` where `name` LIKE %Television% and `status` = 1)

我的搜索功能

public function searchProducts(Request $request) {
        $product = $request->input('product');

        $categories = Category::with('categories')->where(['parent_id' => 0])->get();

        $productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
                                    ->where('name', 'LIKE', "%{$product}%")
                                    ->where('status', 1)->get();


        $breadcrumb = "<a href='/'>Home</a> / ".$product;

        return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));

    }

我的类别模型

class Category extends Model implements Searchable
{
    protected $table = 'categories';
    protected $fillable = [
        'name'
    ];
    public function categories(){
        return $this->hasMany('App\Category','id');
    }

    public function products(){
        return $this->hasMany('App\Product','id');
    }
}

我的产品模型

class Product extends Model implements Searchable
{

    public function category() {
        return $this->hasMany('App\Category', 'id') ;
    }

    public function attributes(){
        return $this->hasMany('App\Product','id');
    }
}

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    您在多个表中都有状态列。 改变这个

    ->where('status', 1)->get();
    

    到这里

    ->where('products.status', 1)->get();
    

    【讨论】:

      【解决方案2】:

      我可以通过如下修改我的搜索功能来解决它​​。

      public function searchProducts(Request $request) {
              $product = $request->input('product');
      
              $categories = Category::with('categories')->where(['parent_id' => 0])->get();
      
              $productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
                                          ->where('categories.name', 'LIKE', "%{$product}%")
                                          ->orWhere('products.product_name', 'LIKE', "%{$product}%")
                                          ->where('products.status', 1)->get();
      
      
              $breadcrumb = "<a href='/'>Home</a> / ".$product;
      
              return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));
      
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-03
        • 1970-01-01
        • 2019-09-20
        • 1970-01-01
        相关资源
        最近更新 更多