当使用Laravel分页时,检索表的ID列


Retrieve the ID column of a table when using Laravel Paginate

我有以下Laravel Fluent查询从博客返回分页结果。我试图在输出中包括来自Posts表的id列,但视图中的$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一样,而不破坏分页?

谢谢!

posts和blog_categories都有自己的id字段,所以它只是默认为第一个记录,通常只是"1"。我会考虑使用Eloquent ORM来解决这个问题。

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

然后你可以这样做:

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

And from the view:

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

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

工作版本:

数据库迁移/

    // 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();

Post模型

class Post extends Eloquent {
    public function Category()
    {
        return $this->belongs_to('Category','category_id');
    }               
}
<<p> 类别模型/strong>
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";
}