简体   繁体   English

通过 SOQL 检索 SObject 行而不查询请求的字段错误不会出现

[英]SObject row was retrieved via SOQL without querying the requested field error is not coming

This trigger is first inserting related contact when account is inserted and then updating a custom field on Account name 'Client_Contact__c' with inserted contact lastname.此触发器首先在插入帐户时插入相关联系人,然后使用插入的联系人姓氏更新帐户名称“Client_Contact__c”上的自定义字段。

trigger practicetrigger on Account ( after insert ) {
        if ( Trigger.isinsert && Trigger.isafter ) {
           Set<Id> accId = new Set<Id>();
           list<Contact> conList = new list<Contact>();
           list<Account> accToUpdate = new list<Account>();
           map<Id, Account> accMap = new map<Id, Account>();
        for ( Account a : Trigger.New ) {
           Contact c = new Contact( LastName = a.Name, AccountId=a.Id );
           conList.add ( c );
           accId.add( a.Id );
        }
        if ( !conList.isempty() ) {
           insert conList;
        }
        for ( Account ac : **[select Id from Account where Id =: accId]** ) {
           ac.Client_Contact__c = ' new contact ';
           system.debug( 'Account ac '+ac.Client_Contact__c);
           accMap.put( ac.Id , ac );
        }
        if ( conList.size() > 0 ) {
           for ( Contact con : conList ) {
               if ( accMap.containskey( con.AccountId ) ) {
                    accMap.get( con.AccountId ).Client_Contact__c = con.lastname;
                    System.debug( ' accMap '+accMap.get(con.AccountId));
                    accToUpdate.add( accMap.get(con.AccountId) );
               }
           }
        }
        if ( !accToUpdate.isempty() ) {
           update accToUpdate;
        }
       }
    }

In the bold part of code, I have not queried the custom field Client_Contact__c but still error is not coming and code is executing successfully.在代码的粗体部分,我没有查询自定义字段 Client_Contact__c 但仍然没有出现错误并且代码正在成功执行。 Why error is not coming?为什么没有出现错误? Can anybody tell what i am missing here and In what situation this error do not come?谁能告诉我这里缺少什么以及在什么情况下不会出现此错误?

You can always set a field to new value even if you didn't query it.您始终可以将字段设置为新值,即使您没有查询它也是如此。 Not sure what you think the problem is?不确定您认为问题出在哪里?

In a normal database and SQL you can do UPDATE TABLE Users SET Name = 'Joe' WHERE Id = 123 , why something similar shouldn't be possible in Apex?在普通数据库和 SQL 中,您可以执行UPDATE TABLE Users SET Name = 'Joe' WHERE Id = 123 ,为什么类似的东西在 Apex 中不应该是可能的? With different syntax, yes - but still, same idea?使用不同的语法,是的 - 但仍然是相同的想法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM