laravel mongodb不保存

时间:2014-06-23 11:45:17

标签: php mongodb laravel

documentation没有详细介绍如何将数据保存到mongodb。

我已经安装了全新的laravel并设置了mongo连接,就像在文档中一样,安装了mongodb本身。

创建了一个模型

use Jenssegers\Mongodb\Model as Eloquent;

class Notifications extends Eloquent {

    protected $connection = 'mongodb';
    protected $collection = 'notifications';

    public static function foo()
    {
        return 'test returning from model';
    }

}

创建一个简单的测试路径

Route::get('notifiction' , function(){

    $notifiction = new Notifications();

    $arr = array('name' => 'John Doe');

    $notifiction->save($arr);
});

但是当我运行localhost / mongo / public / notifiction时,我得到哎呀,看起来出了问题。我不确定还有什么需要通过laravel将信息保存到mongodb?

3 个答案:

答案 0 :(得分:4)

此错误最有可能与质量分配有关。在将其保存到数据库之前,laravel会将每件事视为不安全。因此,我们必须将我们试图保存的字段列入白名单。

我们这样做的方式是在模型中。假设您正在尝试使用UsersUSER model表中保存数据。首先打开app/models/user.php并添加以下行:

class User extends Eloquent {
protected $fillable = ['name'];

}

上面,在fillable中我们列出name因为我们想要从控制器保存名称(如果你在数组中有任何额外的数据填充)。现在我们可以从控制器中保存数据。

例如:User::create(array('name' => 'John'));会在Users collection中保存名称。请注意,除非另有说明,否则集合名称将是模型的名称。

[如果这不能解决您的问题,请转到app/config/app.php并设置debug =true启用调试。找到错误并尝试搜索。]

答案 1 :(得分:1)

您不必像SQL模型那样。

你尝试这样的模型

class User extends Moloquent {
    protected $connection = 'mongodb';
    protected $collection = 'collection1';
    protected $fillable = ['_id','userName','passwd'];
}

您可以尝试插入

DB::connection('mongodb')->collection('collection1')
    ->insert(array(
             '_id' => 'H12345',
             'userName' => 'Nithil',
             'passwd' => 'qwoeuig'));

使用Moloquent在使用多个DBS时更方便。对于使用Moloquent,您可以通过将以下内容添加到app/config/app.php中的别名数组来注册MongoDB模型的别名:

'Moloquent' => 'Jenssegers\Mongodb\Model',

这将允许您使用注册的别名,如:

class MyModel extends Moloquent {}

答案 2 :(得分:0)

OP提到错误是由于

  

<强> Did not installed the MongoDB PHP Library

除此之外,要在Laravel进行批量作业,字段应为"white listed""black listed"

要将字段列入白名单,请添加

// name, age, username and email could be mass assigned
protected $fillable = ['name', 'age', 'username', 'email'];

要将字段列入黑名单,请添加

// except _id everything could be mass assigned
protected $guarded = ['_id'];

到您的模型文件