dqhdpppm02183 2015-06-04 05:09
浏览 237
已采纳

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 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退