0

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

谢谢!

4

2 回答 2

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

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

于 2013-01-20T15:19:05.177 回答
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";
}   
于 2013-01-20T18:12:30.207 回答