Php 使用Laravel Paginate时检索表的ID列
我使用以下Laravel Fluent查询返回博客的分页结果。我试图在输出中包括Posts表中的Php 使用Laravel Paginate时检索表的ID列,php,laravel,Php,Laravel,我使用以下Laravel Fluent查询返回博客的分页结果。我试图在输出中包括Posts表中的id列,但视图中的$post->id在分页结果中返回该post的数字键。例如,如果是第三篇文章,$post->id将返回3,即使表中的id类似于24 这是一个问题- $posts = DB::table('posts') ->join('blog_categories', 'blog_categories.id', '=', 'posts.blog_category_id') -
id
列,但视图中的$post->id
在分页结果中返回该post的数字键。例如,如果是第三篇文章,$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);
如何在不破坏分页的情况下检索类似于postID
的id
列
谢谢 帖子和博客类别都有自己的id字段,因此默认为第一条记录,通常仅为“1”。我将研究使用雄辩的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
我不知道您的项目的确切要求,但这应该会让您朝着正确的方向前进。这里有一个可行的版本: 迁移/数据库
// 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 {
}
类别模型
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";
}
foreach(Post::with('Category')->order_by('created_at','desc')->take(10)->get()作为$Post)
{
echo$post->title.“
”;
echo$post->body.“
”;
echo$post->category->name.“
”;
回显“
\n\n”;
}
谢谢,但这似乎不包括分页?我包括take(),这限制了结果。take()和skip()方法是Fluent/Query Builder的一部分。更多信息:您可以同样轻松地使用paginate()选项,因为您也可以使用它。在这里阅读更多:谢谢!我敢肯定这是我第一次尝试,但遇到了一些错误,不管怎样,它都工作得很好。。谢谢:)