Related News block—MATCH AGAINST query with fuel_model?

edited July 2014 in Modules
I'm trying to make a Related News block, but I'm new to this and having trouble implementing the query. I want to use fuel_model so I can use the get_url and get_excerpt_formatted functions. Here's what I have...

<?php $slug = uri_segment(3); if ($slug) : $selected_article = fuel_model('articles', array('find' => 'one', 'where' => array('slug' => $slug))); if (empty($selected_article)) : redirect_404(); else : $id = $selected_article->id; $keywords = $selected_article->keywords; $q = "SELECT *, MATCH(keywords) AGAINST('$keywords') AS score FROM articles WHERE MATCH(keywords) AGAINST('$keywords' IN BOOLEAN MODE) AND id != $id ORDER BY score DESC, post_date DESC LIMIT 3"; $query = $this->db->query($q); $ids = array(); if($query->num_rows() > 0) : foreach($query->result() as $row) : array_push($ids, $row->id); endforeach; $id_in = '('.implode(',', $ids).')'; $articles = fuel_model('articles', array('find' => 'all', 'where' => array('id IN' => $id_in))); // This doesn't work. endif; endif; endif; ?> <?php if($query->num_rows() > 0) : ?> <div class="block more-news"> <h2 class="heading">Related News</h2> <?php foreach($articles as $article) : ?> <h3 class="subheading"><a href="<?=$article->url?>"><?=$article->title?></a></h3> <div class="excerpt"><?=$article->get_excerpt_formatted(200, 'more &raquo;')?></div> <?php endforeach; ?> </div> <?php endif; ?>

Comments

  • edited 10:25PM
    fuel_model is really just a convenience function and is an alias to:
    $CI->load->model('articles_model');
    $CI->articles_model->find_all(); // if "find" => "all"
    $CI->articles_model->find_one(); // if "find" => "one"

    In this case, I would just call the model directly. There is a find_within() method you can use:
    http://docs.getfuelcms.com/libraries/my_model#func_find_within
  • edited 10:25PM
    I'm not quite how to do it.

    $CI->load->model('articles_model'); $articles = $CI->articles_model->find_within(array(1, 2, 3, 6), array('published' => 'yes'));
    I tried that, and a few other combinations, and my page times out.
  • edited 10:25PM
    That syntax looks correct. If you just run that find_within command and nothing else on the page, does it still time out? You can also run the following after the find_within to see the actual query being generated:
    $CI->articles_model->debug_query();
  • edited July 2014
    I found this issue. The query is
    SELECT `articles`.* FROM (`articles`) WHERE `id` IN ('3, 2') AND `articles`.`published` = 'yes' ORDER BY FIELD(id, '3, 2')
    When I need it to be:
    SELECT `articles`.* FROM (`articles`) WHERE `id` IN (3, 2) AND `articles`.`published` = 'yes' ORDER BY FIELD(id, 3, 2)
    I was trying to do $id_in = implode(', ', $ids); and then $articles = $CI->articles_model->find_within(array($id_in));... Changing it to $id_in_array = array_map('intval', $ids); worked. Thanks.
Sign In or Register to comment.