使用Laravel Paginate时检索表的ID列

时间:2013-01-19 19:03:28

标签: php laravel

我有以下Laravel Fluent查询来返回Blog的分页结果。我尝试在输出中包含Posts表中的id列,但View中的$post->id会在分页结果中返回该帖子的数字键。例如,如果它是第三个帖子,$post->id将返回3,即使表中的ID类似于24。

这是查询 -

$posts = DB::table('posts')
    ->join('blog_categories', 'blog_categories.id', '=', 'posts.blog_category_id')
    ->order_by('created_at', 'desc')
    ->paginate(10);

如何在不打破分页的情况下将id列检索为postID之类的内容?

谢谢!

2 个答案:

答案 0 :(得分:1)

帖子和blog_categories都有自己的id字段,所以它只是默认为第一条记录,通常只是“1”。我会研究使用Eloquent ORM来解决这个问题。

http://laravel.com/docs/database/eloquent

然后你可以这样做:

$posts = Post::order_by('created_at', 'desc')->paginate(10);

从观点来看:

@foreach($posts as $post)
    {{ $post->id }}
    {{ $post->blog_cat->.... }}
@endforeach

我不知道您项目的确切要求,但这应该让您朝着正确的方向前进。

答案 1 :(得分:0)

这是一个有效的版本:

<强>迁移/数据库

    // Blog Categories
    Schema::create('categories', function($table) {

        $table->engine = 'InnoDB';      
        $table->increments('id');
        $table->string('name', 255);
        $table->timestamps();   

    });

    // Posts
    Schema::create('posts', function($table) {

        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('category_id')->unsigned();
        $table->string('title', 255);
        $table->text('body');
        $table->timestamps();   

        $table->foreign('category_id')->references('id')->on('categories');

    }); 

    // Fake Data
    $category = new Category;
    $category->name = 'Category 1';
    $category->save();

    $category = new Category;
    $category->name = 'Category 2';
    $category->save();      

    $post = new Post;
    $post->title = 'Blog Post 1';
    $post->body = 'Lorem Ipsum';
    $post->category_id = 2;
    $post->save();

    $post = new Post;
    $post->title = 'Blog Post 2';
    $post->body = 'Lorem Ipsum';
    $post->category_id = 1;
    $post->save();

发布模型

class Post extends Eloquent {
    public function Category()
    {
        return $this->belongs_to('Category','category_id');
    }               
}

类别模型

class Category extends Eloquent {   
}

获取数据......

foreach (Post::with('Category')->order_by('created_at', 'desc')->take(10)->get() as $post)
{
    echo $post->title."<br/>";
    echo $post->body."<br/>";
    echo $post->category->name."<br/>";
    echo "<br/>\n\n";
}