phalcon/incubator-mongodb

Phalcon Incubator MongoDB

v2.0.1 2023-12-30 16:33 UTC

This package is auto-updated.

Last update: 2024-09-05 14:49:21 UTC


README

Discord Packagist Version PHP from Packagist codecov Packagist

问题追踪器

https://github.com/phalcon/incubator/issues

这是什么

一组助手 - 通过 AR 范式简化与 MongoDB 的工作。

助手

Phalcon\Incubator\MongoDB\Helper

集合管理器

管理器控制集合的初始化,记录应用程序中不同集合之间的关系。

use Phalcon\Incubator\MongoDB\Mvc\Collection\Manager;

$di->set(
    'collectionsManager',
    function () {
        return new Manager();
    }
);

集合

用于管理 MongoDB 集合的 ActiveRecord 类。

定义集合

use Phalcon\Incubator\MongoDB\Mvc\Collection;

class RobotsCollection extends Collection
{
    public $code;

    public $theName;

    public $theType;

    public $theYear;
}

$robots = new RobotsCollection($data);

搜索示例

use MongoDB\BSON\ObjectId;

// How many robots are there?
$robots = RobotsCollection::find();

echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = RobotsCollection::find([
    [
        "type" => "mechanical",
    ],
]);

echo "There are ", count(robots), "\n";

// Get and print virtual robots ordered by name
$robots = RobotsCollection::findFirst([
    [
        "type" => "virtual",
    ],
    "order" => [
        "name" => 1,
    ],
]);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = RobotsCollection::find([
    [
        "type" => "virtual",
    ],
    "order" => [
        "name" => 1,
    ],
    "limit" => 100,
]);

foreach (RobotsCollection as $robot) {
    echo $robot->name, "\n";
}

$robot = RobotsCollection::findFirst([
    [
        "_id" => new ObjectId("45cbc4a0e4123f6920000002"),
    ],
]);

// Find robot by using \MongoDB\BSON\ObjectId object
$robot = RobotsCollection::findById(
    new ObjectId("545eb081631d16153a293a66")
);

// Find robot by using id as sting
$robot = RobotsCollection::findById("45cbc4a0e4123f6920000002");

// Validate input
if ($robot = RobotsCollection::findById($_POST["id"])) {
    // ...
}

添加行为

use Phalcon\Incubator\MongoDB\Mvc\Collection;
use Phalcon\Incubator\MongoDB\Mvc\Collection\Behavior\Timestampable;

class RobotsCollection extends Collection
{
    public $code;

    public $theName;

    public $theType;

    public $theYear;
    
    protected function onConstruct()
    {
         $this->addBehavior(
             new Timestampable(
                 [
                     "beforeCreate" => [
                         "field"  => "created_at",
                         "format" => "Y-m-d",
                     ],
                 ]
             )
         );
    }
}