dongwu4834 2019-02-28 23:41
浏览 10

CakePHP 3中相关表的条件

I have issues writing this code correctly. I have companies, categories, companies_tags and tags tables. 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. Can someone help me fix this ?

  • 写回答

1条回答 默认 最新

  • dongnuo4594 2019-03-02 05:23
    关注

    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" ])
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?