【问题标题】:Get user specific information from database using Laravel and AngularJS使用 Laravel 和 AngularJS 从数据库中获取用户特定信息
【发布时间】:2014-05-23 09:33:18
【问题描述】:

我正在使用 Laravel 和 AngularJS 开发一个应用程序。

我的问题是我想从某个用户的表中获取所有信息。

在 routes.php 文件中,我声明了一个组,以便我可以通过以下方式访问所有 cmets:

localhost/project/public/api/cmets.

我还希望能够通过以下方式获取给定用户的所有 cmets:

localhost/project/public/api/comment/id.
Route::group(array('prefix' => 'api'), function() {
    Route::resource('comments', 'CommentController', array('only' => array('index', 'store', 'destroy')));
    Route::get('comment/{id}', function($id) {
       $col = 'user_id';
       return Comments::where($col, '=', $id);
    });
}

使用此代码时出现错误:

错误异常
    Illuminate\Database\Eloquent\Builder 类的对象无法转换为字符串

我可以通过添加得到第一个结果:

return Comment::where($col, '=', $id)->first();

但我想接收给定用户的所有 cmets。这是怎么做到的。

【问题讨论】:

标签: php database angularjs laravel


【解决方案1】:

你需要得到一个结果

return Comments::where($col, '=', $id)->get();

但是你应该将它序列化为 JSON 格式(例如),所以你应该这样做:

$comments = Comments::where($col, '=', $id)->get();
return Response::json(array('success'=>true,'comments'=>$comments->toJson()));

【讨论】:

  • 谢谢!几乎让我失望了,我自己没有找到答案。
【解决方案2】:

Router 要求你返回一个 Response 对象,而不是 Collection、Builder 或其他任何东西 - 因为 Laravel 试图将响应转换为字符串(就像视图发生的那样),但是响应有一个 _toString( ) 方法,其他对象可能不会 - 因此你的错误。

您应该返回一个视图或其他响应(如 JSON),可能执行以下操作:

Route::get('comment/{id}', function($id) {
    $comments = Comments::where('user_id', '=', $id)->get();
    return View::make('myview')->with('comments', $comments);
});

【讨论】:

猜你喜欢
  • 2012-06-18
  • 2014-07-19
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 2018-11-26
  • 1970-01-01
相关资源
最近更新 更多