【问题标题】:Query Laravel many-to-many relationship based on AND not OR基于 AND 而不是 OR 查询 Laravel 多对多关系
【发布时间】:2018-03-17 18:49:10
【问题描述】:

我已经搜索和搜索,但找不到解决方案。我正在使用 Laravel 5.5。

我有一个简单的 3 表系统设置,如下所示:

  • 产品表格
  • option_items 表格
  • option_items_products 表格(数据透视表)

产品型号hasMany option_items option_items belongsToMany 产品

我可以同步和保存,一切都很好。

我什至可以返回似乎有“或”运算符的结果。含义...我可以找到所有具有 option_item.id 4 OR option_item.id 5 OR option_item.id 8

的产品

我想做的是能够根据 option_item 过滤产品,所以我应该能够以某种方式完成获取所有具有 option_item.id 4 和 option_item 的产品.id 5 AND option_item.id 8

结果会更具体,但应该更准确。

希望有人可以就如何进行这样的查询提供一些指导。我正在学习 laravel,但只需要朝着正确的方向前进。

【问题讨论】:

  • 我想你最好也添加你的代码,这样它会帮助别人检查

标签: php mysql laravel laravel-5 laravel-5.5


【解决方案1】:

试试这样:

   $idArray = array("1","2","3"...);
   $productList = Product::  
               //To check that records exists or not.              
                whereHas(
                'optionItems', function ($query)  use ($idArray){
                    $query->whereIn('id', $idArray);
                }
            )        
              //To fetch the matched records.
                ->with(
                    [
                        'optionItems' => function ($query) use ($idArray) {
                            $query->select('*')->whereIn('id', $idArray);
                        },
                    ]
                )
                ->get()
                ->toArray();

【讨论】:

  • 与其他建议相同的问题。当我尝试这样做时,我得到BadMethodCallException Call to undefined method App\Product::whereHas()
  • 我得到了这个工作,但由于它生成的 sql 代码有这个: ``option_items.id` in ('1', '16'))` “in”计算为如果 option_items_id 为 1 或 16,则为 true
【解决方案2】:

你可以这样做:

$optionIds = [2,1];
$users = Product::whereHas('optionItems',function ($q) use ($option_ids){
     $q->whereIn('option_items.id',$optionIds);
})->get();

这表明您在 Product 模型中存在类似的关系:

public function optionItems()
{
     return $this->belongsToMany(OptionItem::class, 'option_items_products')
}

【讨论】:

  • 当我尝试这样做时,我得到BadMethodCallException Call to undefined method App\Product::whereHas()
  • 我的产品模型中有这个:public function option_items() { return $this->belongsToMany('App\OptionItem') ->withTimestamps(); }
  • 如果有帮助,我正在使用数据透视表。我的设置类似于这个例子:easylaravelbook.com/blog/2016/04/06/…
  • @John 如果你在Product 模型中有关系option_items,你应该对whereHas 使用相同的whereHas('option_items' ...。 Laravel 不会将其转换为 camelCase
  • 我得到了这个工作,但由于它生成的 sql 代码有这个: ``option_items.id` in ('1', '16'))` 如果“in”评估为真option_items_id 是 1 或 16
【解决方案3】:

尝试使用雄辩的关系 https://laravel.com/docs/5.5/eloquent-relationships

类似的东西

Products::with(option_items)->whereHas('option_items', function ($q) {
            $q->where('id','==', 1);
        })->get();

使用选项项 ID 为 1 的选项项获取产品;

【讨论】:

  • 问题在于我需要它来引入具有(所有)多个选项的产品。因此,它需要一个选项 id 为 5、6 和 7 的产品。
猜你喜欢
  • 2013-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-11-02
  • 2015-05-29
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 2020-12-15
相关资源
最近更新 更多