假设我有一个名为article
的数据库表,并且为每篇文章分配一个type
(1 =标准文章,2 =赞助文章,等等)。
使用Propel 2,有可能做到以下几点吗?
步骤1:选择type = 1
的10篇最新文章,按降序排列(这是一个没有头脑的)。
$articles = ArticleQuery::create()
->filterByType(1)
->orderByPublishedAt('desc')
->limit(10)
->find();
步骤2:选择type = 2
的2篇随机文章,并随机插入到当前$articles
对象中。这是我不明白的一步。
- 标准文章
- 标准文章
- 随机赞助文章(随机插入)
- 标准文章
- 标准文章
- 随机赞助文章(随机插入)
- 标准文章
- 标准文章
- 标准文章
- 标准文章
- 标准文章
- 标准文章
似乎我应该能够通过编写某种insertRandomSponsoredArticles()
函数来扩展ArticleQuery
类,但我不太确定如何做到这一点。
应该可能。您可以添加自己的终止函数来操作数组。在你的ArticleQuery类中有类似的东西。
public function insertRandomSponsoredArticles(array $articles)
{
$results = $this->find()->toArray();
$count = count($results);
$pos1 = rand(0, $count-1); // Random position 1
$pos2 = rand(0, $count-1); // Random position 2
array_splice($results, $pos1, 0, $articles[0]);
array_splice($results, $pos2, 0, $articles[1]);
return $results;
}
那么可以这样使用:
$articles = ArticleQuery::create()
->filterByType(1)
->orderByPublishedAt('desc')
->limit(10)
->insertRandomSponsoredArticles($randArticles);