Welcome Guest, Not a member yet? Register   Sign In
Models, where, when and why?
#17

(This post was last modified: 11-17-2014, 09:46 PM by bclinton.)

I think what most people would do is use SQL joins to do what you are doing and select that information in one query.

Your post has an author and a category, but there's no reason the author and category have to come from their own models.  Sure, you may have author and category models in place for other parts of your application, for when you read, create and update those entities.  But you don't have to necessarily use them here.

I would think your post model could look something like this, depending on your table structure.


PHP Code:
public function get_data($postID
{
    $this->db->select(post.id as post_idpost.title as titlepost.content as content);
    $this->db->select(users.id as user_idusers.username as author);
    $this->db->select(category.id as category_idcategory.name as category);

    $this->db->join('users','users.id = post.author');
    $this->db->join('category','category.id = post.category');

    $this->db->where('id'$postID);

    $query $this->db->get('post');

    if ($query->num_rows() > 0)
    {
        return 
$query->result_array()[0]
    


Just doing that off the top of my head, so I'm sure it's missing a semicolon and/or a quote here and there, but you probably get the idea.

The way I look at it is that "post" is a view of an entity with attributes.  Some of those attributes may come from other tables, but that's ok.  Your models don't have to be exact representations of database tables.  You can write a function that returns the view of a post that you need without overthinking it and embedding models within models.
Reply


Messages In This Thread
Models, where, when and why? - by Thyrosis - 10-24-2014, 12:03 AM
RE: Models, where, when and why? - by Rufnex - 10-24-2014, 02:39 AM
RE: Models, where, when and why? - by navotjer - 10-24-2014, 04:10 AM
RE: Models, where, when and why? - by InsiteFX - 10-24-2014, 04:44 AM
RE: Models, where, when and why? - by kilishan - 10-24-2014, 08:17 AM
RE: Models, where, when and why? - by Thyrosis - 10-25-2014, 02:16 AM
RE: Models, where, when and why? - by John_Betong - 10-24-2014, 10:04 AM
RE: Models, where, when and why? - by Hobbes - 10-29-2014, 06:41 AM
RE: Models, where, when and why? - by jlp - 10-29-2014, 08:50 PM
RE: Models, where, when and why? - by albertleao - 10-30-2014, 11:41 AM
RE: Models, where, when and why? - by InsiteFX - 10-30-2014, 04:28 PM
RE: Models, where, when and why? - by Thyrosis - 11-01-2014, 01:27 AM
RE: Models, where, when and why? - by alroker - 11-16-2014, 11:55 AM
RE: Models, where, when and why? - by Thyrosis - 11-18-2014, 05:51 AM
RE: Models, where, when and why? - by RobertSF - 11-20-2014, 08:19 PM
RE: Models, where, when and why? - by veedeoo - 11-17-2014, 09:04 PM
RE: Models, where, when and why? - by bclinton - 11-17-2014, 09:32 PM



Theme © iAndrew 2016 - Forum software by © MyBB