简体   繁体   English

CakePHP 3中相关表的条件

[英]Conditions on related table in CakePHP 3

I have issues writing this code correctly. 我在正确编写此代码时遇到问题。 I have companies , categories , companies_tags and tags tables. 我有companiescategoriescompanies_tagstags表。 The relations are as follow (baked automatically) : 关系如下(自动烘焙):

// 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'
        ]);

I have to select companies which name, category name, or one of its tag name contains a specific text. 我必须选择名称,类别名称或其标签名称之一包含特定文本的公司。

$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 . "%",
                    ]
                    ]);

This query is what I can imagine, but it seems like my LEFT JOIN on tags is not working. 这个查询是我可以想象的,但是好像我在tags上的LEFT JOIN无法正常工作。 Can someone help me fix this ? 有人可以帮我解决这个问题吗?

you can do it like that. 你可以那样做。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM