dqhdpppm02183
2015-06-04 05:09 阅读 58
已采纳

Yii2 elasticsearch setAttributes()不起作用

I am using Yii 2.1 and Yii2-elasticsearch 2.0.3 with a elasticsearch 1.5.0 server to try and index a Member model for a more powerful search. I have a common\indexes\Member model that extends yii\elasticsearch\ActiveRecord and set up the attributes I want to index.

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'];
    }
}

I am having trouble setting the attributes I want in the common\indexes\Member model.

I am creating a new instance of the object and trying to set the attribute values via the ActiveRecord setAttributes() method but it doesn't seem to set any values.

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

This seems to create an empty record. If I manually set the attributes one by one everything seems to work and a record with the correct attributes is created in the elasticsearch database.

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

Am I using the setAttributes() method incorrectly for elasticsearch ActiveRecord's? Do I need to set up my elasticsearch Model differently?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doujiaohuo1096 doujiaohuo1096 2015-06-04 05:22

    By default setAttributes only sets attributes that have at least a single validation rule defined or those that are - as a minimum - defined as being "safe" (either via safeAttributes() or via the safe-validator).

    You can force it to assign everything by just changing the call to

    $index->setAttributes([
       'given_name' => 'Test', 
       'family_name' => 'User', 
       'email' => 'test.member@test.com'
    ], false);
    

    This tells it it is okay to also assign non-safe attributes. But I usually prefer to make sure the validation is configured correctly

    点赞 评论 复制链接分享

相关推荐