jenssegers/mongodb-lite

适用于 Laravel 4 的轻量级 MongoDB 数据库库和模型

v1.1.0 2014-06-02 08:04 UTC

This package is auto-updated.

Last update: 2024-08-25 19:42:28 UTC


README

Build Status Coverage Status

https://github.com/jenssegers/laravel-mongodb 的精简版

完整版与精简版之间的区别如下

  • 具有可配置连接的数据库管理器
  • 具有访问器和修改器的基本模型类
  • 使用原始 MongoCollection 操作
  • 高级 Eloquent 操作,如关系
  • 查询构建器支持

这个精简版返回原生 PHP MongoDB 集合对象,而不是隐藏在查询构建器后面。这对于想要使用原始方法进行高级 MongoDB 操作的人来说可能很有用。

它还附带了一个基本的类似 Eloquent 的模型,以提供额外的灵活性。有关此模型的更多信息,请见下文。

安装

使用 composer 安装

composer require jenssegers/mongodb-lite

app/config/app.php 中添加服务提供者

'Jenssegers\Mongodb\Lite\MongodbServiceProvider',

配置

app/config/database.php 中更改默认数据库连接名称

'default' => 'mongodb',

并添加新的 mongodb 连接

'mongodb' => array(
    'driver'   => 'mongodb',
    'host'     => 'localhost',
    'port'     => 27017,
    'username' => 'username',
    'password' => 'password',
    'database' => 'database'
),

获取集合

一旦配置就绪,您可以通过以下方式访问您的集合

DB::collection('users');

这返回与 'mongodb' 连接项关联的 MongoCollection 对象。如果您想使用不同的连接,请使用

DB::connection('mongodb2')->collection('users');
// A MongoCollection object

因为这是返回原生 MongoCollection 对象,所以您可以使用所有标准方法

$users = DB::collection('users')->find();
$count = DB::collection('users')->count();
$user = DB::collection('users')->findOne(array('name' => 'John Doe'));

模型

模型提供了一种更灵活的方式来访问集合。

use Jenssegers\MongodbLite\Model as Eloquent;

class User extends Eloquent {

	protected $collection = 'users';

}

您也可以在这里使用所有标准 MongoCollection 操作

$users = User::find();

集合

模型返回的所有多结果集都返回一个 Laravel Collection 对象。该对象实现了 IteratorAggregate PHP 接口,因此可以像数组一样迭代。然而,该对象还具有各种其他有助于处理结果集的方法。更多信息请参阅 https://laravel.net.cn/docs/eloquent#collections

$users = User::all();
// Will return a collection of User objects

// Do laravel-collection operations
$user = $users->first();
$count = $users->count();

访问器 & 修改器

由于返回的是模型对象,因此您仍然可以定义自定义方法并使用访问器和修改器。更多信息请参阅 https://laravel.net.cn/docs/eloquent#accessors-and-mutators

use Jenssegers\MongodbLite\Model as Eloquent;

class User extends Eloquent {

	protected $collection = 'users';

	// Accessor
	public function getAvatarAttribute()
	{
		$hash = md5($this->attributes['email']);
		return "http://www.gravatar.com/avatar/$hash";
	}

	// Mutator
	public function setPasswordAttribute($value)
	{
		$this->attributes['password'] = crypt($value);
	}
}

然后可以像这样使用

$user = User::findOne(array('_id' => new MongoId('47cc67093475061e3d9536d2')));
echo $user->avatar;

插入、更新、删除

要从模型在数据库中创建新记录,只需创建一个新的模型实例并调用 save 方法。

$user = new User;
$user->name = 'John Doe';
$user->save();

要更新模型,您可以检索它,更改一个属性,并使用 save 方法

$user->age = 35;
$user->save();

要创建新模型,请使用

$user = User::create(array('name' => 'John'));

要删除模型,只需在实例上调用 delete 方法

$user->delete();

转换为数组 / JSON

您可以将模型或模型集合转换为数组或 JSON,就像在 Eloquent 中一样

$user->toArray();
$user->toJson();