function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Oleg LavvrynenkoOleg Lavvrynenko 

Problem with SObject in trigger

I started to write my first trigger at Apex, but surprisingly get such error after inserting data in Opportunities tab:
Apex trigger AddProject caused an unexpected exception, contact your administrator: AddProject: execution of AfterInsert caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Opportunity.Account: Trigger.AddProject
Here iis  my code:
trigger AddProject on Opportunity (after update,after insert) {
List<Project__c> insertList = new List<Project__c>();
  for (Opportunity opp : 
 [SELECT Name,OwnerId,Description,Id,AccountiD FROM Opportunity WHERE Probability>=0.8 
  AND Id IN :Trigger.New] )
{
  Project__c pr;
  try
  {
   pr=[SELECT Name FROM Project__c WHERE Opportunity_MDR__r.Id=:opp.Id LIMIT 1];
  }
 catch (Exception e)
  {}
  if (pr==null)
  {
  Project__c newProject=new Project__c(Name = opp.Name, OwnerId__c = opp.OwnerId,
  Description__c = opp.Description, Opportunity_MDR__c = opp.Id,Primary_contact__c =opp.Account.Primary_Contact__c);
  insertList.add(newProject);
  // opp.Project_c=newProject;
 System.debug('what a success');
  }
}
try
{
if (insertList!=null)
insert insertList;
}  catch (Exception e) 
 {
  System.debug('Unexpected error has happened  '+ e.getMessage());
 }
}
How can I fix this problemm?
 
William TranWilliam Tran
Replace this:

04  [SELECT Name,OwnerId,Description,Id,AccountiD FROM Opportunity WHERE Probability>=0.8
05   AND Id IN :Trigger.New] 

with this:

[SELECT Name,OwnerId,Description,Id,AccountiD, Account.Primary_Contact__c FROM Opportunity WHERE Probability>=0.8
AND Id IN :Trigger.New] 

Thx
Oleg LavvrynenkoOleg Lavvrynenko
It's OK now, thanks.
Luciano StragaLuciano Straga
Every time you need information of a field that belongs to an object that was queried in a SOQL query, every time you need to include that field in the SOQL query.