1
votes

This is my tables data.

  • categories [id] [category_name]

  • posts [id] [category_id] [post_name]

What i want to do is:

I want to list posts and join categories table for echo category_name.


This is my controller

class Form_data_Controller extends Base_Controller {


    function action_index() {

        $posts = new Post();
        $list_posts = $posts->list_posts();
        $view['list_posts'] = $list_posts;

        echo '<pre>';
        print_r( $list_posts );
        echo '</pre>';

        $view['pagination'] = $list_posts->links();

        // page title
        $view['page_title'] = 'Test list data';

        // create view and end.
        return View::make( 'form-data.index_v', $view );

    }// action_index


}

This is post model

class Post extends Eloquent {


    //public static $table = 'posts';


    public function categories() {
        return $this->belongs_to( 'Category' );
    }// categories


    function list_posts() {
        $query = $this
                ->order_by( 'post_name', 'asc' )
                ->paginate( '10' );

        return $query;
    }// list_posts


}

This is category model

class Category extends Eloquent {


    //public static $table = 'categories';


    public function posts() {
        return $this->has_many( 'Post' );
    }// categories


}

I want to list posts from post model -> list_posts() method because i want it done in model Not controller, but i cannot join categories table to get category_name.

How to join categories table to get category_name?

1

1 Answers

0
votes

Multiple controller methods may need to "list posts" differently, so I wouldn't put that logic in the model. This is how I think you should accomplish your problem. Otherwise, you can make that a static method and call it as $posts = Post::list_posts();

class Form_data_Controller extends Base_Controller {

    function action_index() {

        $posts = Post::order_by( 'post_name', 'asc' )->paginate( '10' );

        return View::make( 'form-data.index_v')
                  ->with('title', 'Test list data')
                  ->with('posts', $posts);
    }
}

//application/models/Post.php

class Post extends Eloquent {

    //public static $table = 'posts';

    public function category() {
        return $this->belongs_to( 'Category', 'category_id' );
    }
}

//application/models/Category.php

class Category extends Eloquent {

    //public static $table = 'categories';

    public function posts() {
        return $this->has_many( 'Post' );
    }// categories
}

//application/views/form-data/index_v.blade.php

<html>
<head>
<title>{{ title }}</title>
</head>
<body>
 {{ $posts->links() }}
@foreach($posts as $post)
 {{ $post->category->name }}
@endforeach
</body>
</html>