【问题标题】:Laravel Repositories whereHas -- multipleLaravel 存储库 whereHas -- 多个
【发布时间】:2023-03-14 15:31:01
【问题描述】:

我有以下存储库Products,每个产品可以有很多Categories和很多Bidders

我想要实现的是以下(没有存储库)

$products = Products::whereHas('categories', function ($category) {


})->whereHas('bidders', function ($bidder) {

})->get();

这很好用,但是,我正在尝试使存储库就位,并且您仍然可以执行whereHas 查询,因此在我的存储库中我创建了一个方法:

public function whereHas($attribute, \Closure $closure = null)
{
    return $this->model->whereHas($attribute, $closure);
}

这很好用,但前提是我在主查询中使用其中一个,而如果我使用多个:

$products = $this->products->whereHas('categories', function ($category) {
   $category->where('id', '=', 1);
})->whereHas('bidders', function($bidders) {

})->get();

我收到以下错误:

Unknown column 'has_relation'

找不到列:1054 未知列 'has_relation' 在 'where 子句' (SQL: select * from products where exists (select * from categories 内部连接 ​​products_categories categories.id = products_categories.categories_id 其中products.id = products_categories.products_idid = 1) 和 (has_relation = 部分))

我看到的问题是它在第一个 whereHas 上返回一个项目集合,这意味着它无法计算第二个。关于我哪里出错的任何想法?

【问题讨论】:

    标签: laravel eloquent repository-pattern


    【解决方案1】:

    您可以将具有多个关系的闭包传递给whereHas

    $products = $this->products->whereHas(['categories', function 
            ($category) {
      $category->where('id', '=', 1);
    },'bidders' => function($bidders) {
    
    }])->get();
    

    它将按预期工作。

    【讨论】:

      猜你喜欢
      • 2014-11-29
      • 2021-07-01
      • 2023-03-09
      • 1970-01-01
      • 2016-06-17
      • 2019-06-09
      • 2015-02-08
      • 2022-01-22
      • 2014-01-11
      相关资源
      最近更新 更多