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)
来自您应用程序的任何位置
阅读文档将有很大帮助.
Kou*_*Das 18
有三种方法可以做到这一点.
1.
$entireTable = TableModelName::all();
Run Code Online (Sandbox Code Playgroud)
例如,
$posts = Posts::get();
Run Code Online (Sandbox Code Playgroud)
将此行放在控制器中的类之前
使用DB;
现在在课堂上
$posts = DB::table('posts')->get(); // it will get the entire table
Run Code Online (Sandbox Code Playgroud)
将此行放在控制器中的类之前
使用DB;
现在在控制器中
$posts = DB::select('SELECT * FROM posts');
Run Code Online (Sandbox Code Playgroud)
好吧,要用 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
去你的控制器写这个功能
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)