【问题标题】:Retrieving and displaying MongoDB document content in Laravel 4 with Jenssegers Laravel library使用 Jenssegers Laravel 库在 Laravel 4 中检索和显示 MongoDB 文档内容
【发布时间】:2014-06-30 12:35:17
【问题描述】:

我是 Laravel 的新手。我正在使用 Jenssegers Laravel 库,这是一个支持 MongoDB 的雄辩的模型和查询构建器。

在我的数据库中,我创建了下面的文档。我试图在浏览器上显示文档的内容,但没有成功。

对于如何在 Laravel 4 上检索和显示 MongoDB 文档的内容,我将不胜感激。

谢谢。

{
"_id" : ObjectId("537124d584142189174ce113"),
"username" : "usertest",
"password" : "passtest",
"email" : "test@email.com",
"school" : "College university",
"country" : "USA",
"state" : "Washington",
"city" : "Seattle"
}

这是我到目前为止得到的代码..

文件:/app/models/User.php

<?php
use Jenssegers\Mongodb\Model as Eloquent;


class User extends Eloquent {

    /**
     * The database table (collection) used by the model.
     *
     * @var string
     */
     protected $collection = 'user';

     $users = User::all();

     public function all()
     {
        return $this->$users;
     }
}

文件:/app/routes.php

Route::get('users', function()
{
return View::make('users')->with('user',$users);

});

文件:/app/views/users.blade.php

@extends('layout')

@section('content')
    @foreach($users as $user)
        <p>{{ $user->name }}</p>
    @endforeach
@stop

文件:/app/views/layout.blade.php

<html>
    <body>
        <h1>Laravel Quickstart</h1>

        @yield('content')
    </body>
</html>

【问题讨论】:

  • 您不必在模型中定义“所有功能”,它已经在 Eloquent 中受到挑战。 Mongo 库的工作也类似。因此,请尝试在控制器或路由中使用“User::all()”。可以直接打印。我建议你先检查一下 Eloquent Documentation laravel.com/docs/eloquent

标签: mongodb laravel-4 jenssegers-mongodb


【解决方案1】:

也许这很明显,但如果你想在视图中使用users 变量:

@foreach($users as $user)
// some code
@endforeach

那么在路由(或控制器)中,您应该通过users 而不是user

// should be
return View::make('users')->with('users',$users);

// not    
return View::make('users')->with('user',$users);

另外,我宁愿将 User::all() 放在路由/控制器中,然后放在模型中,因为就像 Muharrem Tigdemir 在评论中提到的那样 - 它已经在 Eloquent 中声明了。它看起来像这样:

Route::get('users', function()
{
    return View::make('users')->with('user', User::all());

});

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    在您的文档中您有 username,但在 users.blade.php 文件中您引用的是 &lt;p&gt;{{ $user-&gt;name }}&lt;/p&gt;

    应该是&lt;p&gt;{{ $user-&gt;username }}&lt;/p&gt;

    【讨论】:

      猜你喜欢
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      • 2016-11-19
      • 1970-01-01
      • 2017-05-18
      • 2018-07-10
      • 2014-08-04
      相关资源
      最近更新 更多