1

Let's say I have a database table called article, and each article is assigned a type (1 = standard article, 2 = sponsored article, etc.).

Using Propel 2, is it possible to do the following?

Step 1: Select the 10 latest articles, ordered descending, of type = 1 (This is a no brainer).

$articles = ArticleQuery::create()
    ->filterByType(1)
    ->orderByPublishedAt('desc')
    ->limit(10)
    ->find();

Step 2: Select 2 random articles of type = 2 and randomly insert them into the current $articles object. This is the step where I'm at a loss.

For example, the final resulting selection would look something like this:

  1. Standard Article
  2. Standard Article
  3. Random Sponsored Article (inserted here randomly)
  4. Standard Article
  5. Standard Article
  6. Random Sponsored Article (inserted here randomly)
  7. Standard Article
  8. Standard Article
  9. Standard Article
  10. Standard Article
  11. Standard Article
  12. Standard Article

It seems that I should be able to extend the ArticleQuery class by writing some sort of insertRandomSponsoredArticles() function, but I'm not quite sure how to go about this.

Nick S.
  • 353
  • 3
  • 13

1 Answers1

0

It should be possible. You can perhaps add your own terminator function that manipulates the array. Something like this in you ArticleQuery class.

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;
}

Then perhaps use it like this:

$articles = ArticleQuery::create()
    ->filterByType(1)
    ->orderByPublishedAt('desc')
    ->limit(10)
    ->insertRandomSponsoredArticles($randArticles);
Qiniso
  • 2,587
  • 1
  • 24
  • 30