1

这是我的表格数据。

  • 类别[id] [category_name]

  • 帖子[id] [category_id] [post_name]

我想做的是:

我想为 echo category_name 列出帖子并加入类别表。


这是我的控制器

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


}

这是后期模型

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


}

这是类别模型

class Category extends Eloquent {


    //public static $table = 'categories';


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


}

我想列出来自 post model -> list_posts() 方法的帖子,因为我希望它在 model Not 控制器中完成,但我无法加入categories 表来获取category_name

如何加入类别表以获取类别名称

4

1 回答 1

0

多个控制器方法可能需要以不同的方式“列出帖子”,因此我不会将该逻辑放入模型中。这就是我认为你应该完成你的问题的方式。否则,您可以将其设为静态方法并将其称为 $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);
    }
}

//应用程序/模型/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>
于 2013-01-12T18:17:21.043 回答