【问题标题】:Conditions on related table in CakePHP 3CakePHP 3 中相关表的条件
【发布时间】:2019-02-28 23:41:04
【问题描述】:

我在正确编写此代码时遇到问题。我有companiescategoriescompanies_tagstags 表。关系如下(自动烘焙):

// CompaniesTable.php
$this->belongsToMany('Tags', [
            'foreignKey' => 'company_id',
            'targetForeignKey' => 'tag_id',
            'joinTable' => 'companies_tags'
        ]);

$this->belongsTo('Categories', [
            'foreignKey' => 'categorie_id'
        ]);

// CategoriesTable.php
$this->hasMany('Etablissements', [
            'foreignKey' => 'categorie_id'
        ]);

// TagsTable.php
$this->belongsToMany('Companies', [
            'foreignKey' => 'tag_id',
            'targetForeignKey' => 'company_id',
            'joinTable' => 'companies_tags'
        ]);

// CompaniesTags.php
$this->belongsTo('Companies', [
            'foreignKey' => 'company_id',
            'joinType' => 'INNER'
        ]);
        $this->belongsTo('Tags', [
            'foreignKey' => 'tag_id',
            'joinType' => 'INNER'
        ]);

我必须选择名称、类别名称或其标签名称之一包含特定文本的公司。

$ets = (new TableRegistry())
                ->get('Companies')
                ->find('published')
                ->distinct()
                ->contain([
                    "Tags",
                    "Categories"
                    ])
                ->leftJoinWith('Tags', function (\Cake\ORM\Query $q) use ($quoi) {
                    return $q->where(['OR'  => ['Tags.nom LIKE ' => '%' . $quoi . '%', 'Tags.description LIKE' => '%' . $quoi . '%']]);
                })
                ->where(['OR' => ["Companies.nom LIKE" => "%" . $quoi . "%",
                    "Companies.description LIKE" => "%" . $quoi . "%",
                    "Categories.description LIKE" => "%" . $quoi . "%",
                    "Categories.nom LIKE" => "%" . $quoi . "%",
                    ]
                    ]);

这个查询是我可以想象的,但似乎我在tags 上的 LEFT JOIN 不起作用。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 看起来你在左连接上的条件应该是where ?您确定要加入关联中定义的键,并且仅根据名称和描述进行过滤吗?
  • 谢谢@Greg Smidt,我想选择具有与用户搜索的文本匹配的类别或标签的公司。 Companies 与 Categories 具有“belongTo”关系,与 Tags 具有“manyToMany”关系。
  • 明白。但是您需要 join 键,而不是名称或描述。然后过滤那些使用where

标签: php cakephp cakephp-3.0


【解决方案1】:

你可以这样做。

->contain(["Tags" => function (Query $query, $quoi) {
return $query->select(['field_1', 'field_2'])
    ->where(['OR'  => ['Tags.nom LIKE ' => '%' . $quoi . '%', 'Tags.description LIKE' => '%' . $quoi . '%']]); }, "Categories" ])

【讨论】:

  • 这并不能解决我的问题。也许,我需要使用一些策略来解决它。谢谢。
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多