我们需要在哪个文件夹中添加 laravel4 中的数据库查询


In which folder we need add database query in laravel4?

我是laravel的初学者,已经安装了laravel4,它的工作很酷。甚至我已经完成了数据库配置。如果我想获取或插入或执行一些需要编写数据库查询的数据库操作?我在路由器中编写了一个简单的代码.php如下所示,并从数据库中获取所有值。但是我需要知道我们到底需要在哪里编写此代码片段?我的是编写一个休息 API。请有人帮我吗?

 $users = DB::table('user')->get();
 return $users;

这取决于您如何设计路由。 如果你像这样路由

Route::get('/', array('as' => 'home', function () {
 }));

然后,您可以在路由页面中进行查询,例如

Route::get('/', array('as' => 'home', function () {
   $users = DB::table('user')->get();
    return $users;
 }));

但是,如果您在路由中调用控制器,例如

Route::get('/', array('as' => 'home', 'uses' => 'HomeController@showHome'));

然后你可以在控制器showHome方法HomeController查询喜欢

class HomeController extends BaseController {
    public function showHome(){
          $users = DB::table('user')->get();
          return $users;
    }
}

注意:控制器目录app/controllers

更新

如果您想使用Model那么您需要App/models文件夹中创建模型,例如

class User extends Eloquent {
    protected $table = 'user';
    public $timestamps = true; //if true then you need to keep two field in your table named `created_at` and `updated_at`
}

那么查询将是这样的

$users = User::all();
return $users;