从Laravel和Eloquent的桌子中选择所有

RSM*_*RSM 29 php mysql laravel eloquent laravel-4

我正在使用Laravel 4设置我的第一个模型来从一个名为的表中提取所有行posts.

在标准MySQL中我会使用:

SELECT * FROM posts;
Run Code Online (Sandbox Code Playgroud)

我如何在Laravel 4模型中实现这一目标?

请参阅下面的完整模型源代码:

<?php

class Blog extends Eloquent 
{

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'posts';

    public function getAllPosts()
    {

    }

}
Run Code Online (Sandbox Code Playgroud)

Stu*_*urm 63

你只需打电话

Blog::all();

//example usage.
$posts = Blog::all();

$posts->each(function($post) // foreach($posts as $post) { }
{
    //do something
}
Run Code Online (Sandbox Code Playgroud)

来自您应用程序的任何位置

阅读文档将有很大帮助.

  • 小心使用`:: all()`因为它从表中读取_everything_到内存中.如果您的表有很多记录,那么您可以通过这种方式快速超过PHP的内存限制.解决方案显然是使用`Builder :: cursor()`或`Builder :: chunk()`. (4认同)
  • 如果达到 apache 的最大内存限制,您将收到“Blog::all();”的 500 错误消息 (2认同)

Kou*_*Das 18

有三种方法可以做到这一点.

1.

$entireTable = TableModelName::all();
Run Code Online (Sandbox Code Playgroud)

例如,

$posts = Posts::get(); 
Run Code Online (Sandbox Code Playgroud)
  1. 将此行放在控制器中的类之前

    使用DB;

现在在课堂上

$posts = DB::table('posts')->get(); // it will get the entire table
Run Code Online (Sandbox Code Playgroud)
  1. 将此行放在控制器中的类之前

    使用DB;

现在在控制器中

$posts = DB::select('SELECT * FROM posts');
Run Code Online (Sandbox Code Playgroud)


Kol*_*lby 7

好吧,要用 eloquent 做到这一点,你会这样做:

Blog:all();
Run Code Online (Sandbox Code Playgroud)

在您的模型中,您可以:

return DB::table('posts')->get();
Run Code Online (Sandbox Code Playgroud)

http://laravel.com/docs/queries


Cha*_*ndo 7

去你的控制器写这个功能

public function index()
{
  $posts = \App\Post::all();

  return view('yourview', ['posts' => $posts]);
}
Run Code Online (Sandbox Code Playgroud)

为了展示它

@foreach($posts as $post)
  {{ $post->yourColumnName }}
@endforeach
Run Code Online (Sandbox Code Playgroud)