Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Yii2 Redis Laravel Package

yiisoft/yii2-redis

Yii2 Redis extension providing Redis-backed cache, mutex, and session handlers plus an ActiveRecord layer for storing and querying structured data in Redis. Requires Redis 2.6.12+ and PHP 7.4+ (best on PHP 8).

View on GitHub
Deep Wiki
Context7

Использование ActiveRecord

Для получения общей информации о том, как использовать Yii ActiveRecord, обратитесь к руководству. Для определения redis ActiveRecord класс записи должен расширяться от класса [[yii\redis\ActiveRecord]] и реализовывать хотя бы метод attributes() для определения атрибутов записи. Первичный ключ может быть определен с помощью [[yii\redis\ActiveRecord::primaryKey()]] который по умолчанию имеет значение id если не указано. Первичный ключ должен быть частью атрибутов, поэтому убедитесь, что атрибут id определен, если вы не указали свой собственный первичный ключ.

Ниже приведен пример модели Customer:

class Customer extends \yii\redis\ActiveRecord
{
    /**
     * [@return](https://github.com/return) array the list of attributes for this record
     */
    public function attributes()
    {
        return ['id', 'name', 'address', 'registration_date'];
    }

    /**
     * [@return](https://github.com/return) ActiveQuery defines a relation to the Order record (can be in other database, e.g. elasticsearch or sql)
     */
    public function getOrders()
    {
        return $this->hasMany(Order::className(), ['customer_id' => 'id']);
    }

    public static function find()
    {
        return new CustomerQuery(get_called_class());
    }
}

class CustomerQuery extends \yii\redis\ActiveQuery
{
    /**
     * Defines a scope that modifies the `$query` to return only active(status = 1) customers
     */
    public function active()
    {
        return $this->andWhere(['status' => 1]);
    }
}

Общее использование redis ActiveRecord очень похоже на БД ActiveRecord как описано в руководстве. Он поддерживает тот же интерфейс и функции, за исключением следующих ограничений:

  • Поскольку redis не поддерживает SQL, API запросов ограничен следующими методами: where(), limit(), offset(), orderBy() и indexBy(). (orderBy() еще не реализовано: #1305)
  • via-отношения не могут быть определены через таблицу, поскольку в redis нет таблиц. Вы можете определять отношения только через другие записи.

Также можно определить отношения от redis ActiveRecords до обычных классов ActiveRecord и наоборот.

Например:

$customer = new Customer();
$customer->attributes = ['name' => 'test'];
$customer->save();
echo $customer->id; // id will automatically be incremented if not set explicitly

$customer = Customer::find()->where(['name' => 'test'])->one(); // find by query
$customer = Customer::find()->active()->all(); // find all by query (using the `active` scope)
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle