对包含的模型使用limit() [英] Using limit() on contained model
问题描述
代码
说我有两个模型,分别命名为 Product
和 / code>,它们通过
产品hasMany图像
和链接到图像belongsTo产品
。
现在,假设我要获取所有带有第一张图片的产品。我将使用这个代码:
$ this-> Products-> find('all')
- > contains([
'Images'=> function($ q){
return $ q
- > order('created ASC')
- > limit (1);
}
]);
看起来不错,对吧?除了现在只有一个的产品包含图片,但实际上每个产品至少包含一个图片(如果查询没有限制)。
产生的查询
问题似乎是有限制的,因为这会产生以下两个查询(例如):
SELECT
pre>
Products.id AS`Products__id`,
FROM
产品产品
和
SELECT
Images.id AS `Images__id`,
Images.product_id AS` Images__product_id`,
Images.created AS`Images__created`
FROM
图像
WHERE
Images.product_id in(1,2,3,4,5)
ORDER BY
created ASC
LIMIT 1
查看第二个查询,很明显这将总是只导致一个图像。
问题
但是,当我调用
时,我希望Cake ORM将图像限制为每个产品limit(1)
。
我的问题:这是一个错误,我如何使用ORM?如果是,应如何将图片数量限制为每张图片一张?
解决方案最简单的方法是创建另一个关联:
$ this-> hasOne FirstImage',[
'className'=>'Images',
'foreignKey'=>'image_id',
'strategy'=>'select',
'sort'=> ['FirstImage.created'=>'DESC'],
'conditions'=> function($ e,$ query){
$ query-> limit 1);
return [];
}
])
The Code
Say I have two models, named
Product
andImage
, which are linked byProduct hasMany Image
andImage belongsTo Product
.Now, say I want to fetch all products with the first image each. I would use this code:
$this->Products->find('all') ->contain([ 'Images' => function($q) { return $q ->order('created ASC') ->limit(1); } ]);
Looks about right, right? Except now only one of the products contains an image, although actually each product contains at least one image (if queried without the limit).
The resulting Queries
The problem seems to be with the limit, since this produces the following two queries (for example):
SELECT Products.id AS `Products__id`, FROM products Products
and
SELECT Images.id AS `Images__id`, Images.product_id AS `Images__product_id`, Images.created AS `Images__created` FROM images Images WHERE Images.product_id in (1,2,3,4,5) ORDER BY created ASC LIMIT 1
Looking at the second query, it is quite obvious how this will always result in only one image.
The Problem
However, I would have expected the Cake ORM to limit the images to 1 per product when I called
limit(1)
.My question: Is this an error in how I use the ORM? If so, how should I limit the number of images to one per image?
解决方案The cleanest way you can do this is by creating another association:
$this->hasOne('FirstImage', [ 'className' => 'Images', 'foreignKey' => 'image_id', 'strategy' => 'select', 'sort' => ['FirstImage.created' => 'DESC'], 'conditions' => function ($e, $query) { $query->limit(1); return []; } ])
这篇关于对包含的模型使用limit()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文