是否可以将随机行注入到现有的Propel ORM查询中?



假设我有一个名为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对象中。这是我不明白的一步。

例如,最终的结果选择看起来像这样:
  1. 标准文章
  2. 标准文章
  3. 随机赞助文章(随机插入)
  4. 标准文章
  5. 标准文章
  6. 随机赞助文章(随机插入)
  7. 标准文章
  8. 标准文章
  9. 标准文章
  10. 标准文章
  11. 标准文章
  12. 标准文章

似乎我应该能够通过编写某种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);

最新更新