【问题标题】:Yii2 elasticsearch setAttributes() not workingYii2 elasticsearch setAttributes()不起作用
【发布时间】:2015-06-04 15:14:23
【问题描述】:

我正在使用 Yii 2.1 和 Yii2-elasticsearch 2.0.3 和 elasticsearch 1.5.0 服务器来尝试索引会员模型以获得更强大的搜索。我有一个 common\indexes\Member 模型,它扩展了 yii\elasticsearch\ActiveRecord 并设置了我想要索引的属性。

namespace common\indexes;

use yii\elasticsearch\ActiveRecord;

class Member extends ActiveRecord {

    /**
     * @return array the list of attributes for this record
     */
    public function attributes() {
        // path mapping for '_id' is setup to field 'id'
        return ['id', 'given_name', 'family_name', 'email'];
    }
}

我无法在common\indexes\Member 模型中设置我想要的属性。

我正在创建对象的一个​​新实例并尝试通过 ActiveRecord setAttributes() 方法设置属性值,但它似乎没有设置任何值。

$index = new common\indexes\Member();
$index->setAttributes(['given_name' => 'Test', 'family_name' => 'User', 'email' => 'test.member@test.com']);
$index->save();

这似乎创建了一个空记录。如果我一一手动设置属性,一切似乎都正常,并且在 elasticsearch 数据库中创建了具有正确属性的记录。

$index = new common\indexes\Member();
$index->given_name = 'Test';
$index->family_name = 'User';
$index->email = 'test.member@test.com';
$index->save();

我是否对 elasticsearch ActiveRecord 错误地使用了 setAttributes() 方法?我需要以不同方式设置我的 elasticsearch 模型吗?

【问题讨论】:

  • 您的代码中的错字是您实际从AbstractIndex 定义的,而不是您声称的elasticsearch\ActiveRecord
  • 是的,这是一个错字。

标签: php elasticsearch yii2


【解决方案1】:

默认情况下,setAttributes 只设置至少定义了一个验证规则的属性,或者至少定义为“安全”的属性(通过safeAttributes() 或通过安全验证器)。

您可以通过将调用更改为

来强制它分配所有内容
$index->setAttributes([
   'given_name' => 'Test', 
   'family_name' => 'User', 
   'email' => 'test.member@test.com'
], false);

这告诉它也可以分配非安全属性。 但我通常更喜欢确保the validation 配置正确

【讨论】:

  • 还添加了具有安全属性的 rules() 方法。公共函数规则(){返回[[['email','given_name','family_name'],'safe']];}
  • 这确实是正确的做法。既然您有了验证规则,也许可以按照它们真正应该的那样来制作它们?即如果需要:使用"required"(所有Validators 暗示safe)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-24
  • 2017-09-13
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
相关资源
最近更新 更多