【问题标题】:CakePhp3: Select registers count greater than in relationship Has ManyCakePhp3:选择寄存器计数大于关系有很多
【发布时间】:2017-11-23 14:17:19
【问题描述】:

我怀疑如何解决这个问题。我有两个表,属性和图像有很多关系。一个属性可以有 0,1 个或多个相关图像。我想搜索具有超过 1 张相关图像的属性。我试过了:

$propertiesExclusive = $this->Properties->find('all')->contain( [ 'PropertyTags', 

        'ImagesAffiliates' => function($e){
                        $e->group([ 'ImagesAffiliates.id HAVING (COUNT(ImagesAffiliates.id) > 1 )' ]);

                return $e;

        }])

    ->order(['id' => 'DESC'])->where(['exclusive' => 1])->where($defaultWhere)->limit(7)->all();

这个想法是,如果一个属性没有图像或只有一个,我们就不会得到它。

我尝试了几种形式,但没有办法。

【问题讨论】:

  • 你可以尝试用“匹配”来代替“包含”功能吗? book.cakephp.org/3.0/en/orm/…
  • 我把:->matching([ 'ImagesAffiliates' => function ($q) { return $q->select( [ 'id', 'property_id', 'count' => $q ->func()->count('*') ]) ->group(['property_id']); }]) -> 我在 cakephp3Warning 上有以下错误(2) :explode() 期望参数 2 是字符串,数组给定 [CORE/src/ORM/EagerLoader.php,行 228]
  • @ndm 当您想要获得深度关联并且关系具有条件时,该示例非常有趣,但在我们的示例中,我们需要该条件的计数,然后再次获得条件。我认为对我无效。
  • 您不必使用条件,它们是完全可选的。根据您问题中的描述,您只需要在ImagesAffiliates 上进行内部连接(我想按Properties 分组)。如果您有除当前描述/显示的要求之外的任何其他要求,请更新您的问题以反映这一点。

标签: cakephp orm cakephp-3.0 has-many cakephp-3.x


【解决方案1】:

感谢@adm。你说对了。我不得不将选择与引用“别名”total_images 字段混合在一起。

 $this->Properties->find('all')->contain('ImagesAffiliates')->select([ 'total_images' => $propertiesNew->func()->count('ImagesAffiliates.id'), 'ImagesAffiliates.id' ])
                ->leftJoinWith('ImagesAffiliates')
                ->group(['ImagesAffiliates.property_id'])
                ->enableAutoFields(true)->having(['total_images >' => 2])->limit(7)->all();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    相关资源
    最近更新 更多