如何使用查询构建器根据实际字段中的表进行条件mysql左联接

设置产品时,我可以选择将其可用性限制为客户所在的国家,地区和城市。基于此,我只会向系统中符合此条件的相关客户展示产品。

在某些情况下,我只想将产品设置为一个国家/地区而忽略城市,我想知道如何最好地编写此查询。

我的看法有两种选择。

  1. 如果某个产品与所有城市和地区都相关,则只需将它们全部包含在内(大量数据)。
  2. 如果不需要城市/地区,只需忽略限制城市/城市的声明。

产品:

+---------------------+------------------+------+-----+---------+----------------+
| Field               | Type             | Null | Key | Default | Extra          |
+---------------------+------------------+------+-----+---------+----------------+
| id                  | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| uuid                | binary(16)       | NO   | UNI | NULL    |                |
+---------------------+------------------+------+-----+---------+----------------+

很多到很多位置

+------------------+------------------+------+-----+---------+-------+
| Field            | Type             | Null | Key | Default | Extra |
+------------------+------------------+------+-----+---------+-------+
| product_id          | int(10) unsigned | NO   | PRI | NULL    |       |
| meta_location_id | int(11)          | NO   | PRI | NULL    |       |
+------------------+------------------+------+-----+---------+-------+

位置

+-------------+---------------+------+-----+---------+----------------+
| Field       | Type          | Null | Key | Default | Extra          |
+-------------+---------------+------+-----+---------+----------------+
| id          | int(11)       | NO   | PRI | NULL    | auto_increment |
| iso         | varchar(50)   | YES  |     | NULL    |                |
+-------------+---------------+------+-----+---------+----------------+

查询建筑商代码

$qb = $this->repository->createQueryBuilder('product');
$qb->orderBy('product.id','ASC');

//If we are limiting by country
if (isset($options['country']) and null !== $options['country']) {
    $qb->andWhere('product.country = :country')
        ->setParameter('country',$options['country']);
}

地区/城市:

region选项是客户的当前区域,无论是否发送,我都无法控制。由于我在产品表中进行搜索,因此需要检查产品区域是否存在。如果确实如此,那么我必须将其限制在现有区域内,否则将其忽略。

当前查询: 对于此查询,如果区域不匹配,则不会列出产品。我想将其更改为仅适用于产品表中存在数据的情况。

   if (isset($options['region']) and null !== $options['region']) {
        $qb->leftJoin('product.regions','region');
        ->andWhere(($qb->expr()->in('region',[$options['region']])));
    }

我猜我需要一些东西

    $qb->add('select','CASE WHEN region.id IS NOT NULL then do some query...

任何想法将不胜感激!

kneie 回答:如何使用查询构建器根据实际字段中的表进行条件mysql左联接

这就是我解决此问题的方式。

与其做复杂的事情,例如试图弄清楚一个连接是否包含数据。我只是在我们的元位置表中创建了一个虚拟行。

我们的加入现在看起来像这样:

  if (isset($options['region']) and null !== $options['region']) {
        $qb->leftJoin('product.regions','region');
        ->andWhere(($qb->expr()->in('region',[12345,$options['region']])));
  }

其中12345是虚拟行的ID。

在设置产品时,在下拉菜单中,我有一个名为“任何”的项目,这意味着客户住在哪个区域都没有关系,就像任何区域一样。

因此,如果选择了任何联接,那么联接将有效,否则,如果该区域与实际区域匹配,那么它也将起作用。

好吧,我们拥有了,最简单的解决方案通常是最好的!

本文链接:https://www.f2er.com/3067953.html

大家都在问