Insert new record with a relationship link

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aldisa
    Junior Member
    • Jun 2023
    • 28

    Insert new record with a relationship link

    I have two entities that are related to each other as follows

    Assignment <= Many to One => Account

    In the fields of MySQL table for Assignment, there is a field called `account_id` which contains the `id` of the linked record in the Account table.

    With this in mind, is it possible to insert a new Assignment as follows:

    PHP Code:
    $entity = $entityManager->createEntity('Assignment', [
      'account' => /* id of Account record */,
      /* other data */
    ], $saveOptions); 
    
    If not possible...

    The ORM Docs has a section for how to create a relationship between two entities, but it is not clear to me how insert a single new Assignment record with a link to a single existing Account record specified in it.

    Would it be:

    PHP Code:
    $account = $entityManager->getEntityById('Account', /* id of Account record */);
    
    $assignment = $entityManager->createEntity('Assignment', [
      /* other data */
    ]);
    
    $entityManager->getRDBRepository('Assignment')
      ->getRelation($assignment, 'account')
      ->relate($account); 
    
    Thanks in advance for the guidance
  • item
    Active Community Member
    • Mar 2017
    • 1476

    #2
    PHP Code:
    $entity = $entityManager->createEntity('Assignment', [
      'accountId' => /* id of Account record */,
      /* other data */
    ], $saveOptions);  
    i don't know if this post respect :
    afterRelate or afterUnrelate hook​

    but second solution respect rules of hook and certainly many other think
    Last edited by item; 06-29-2023, 09:47 PM.
    If you could give the project a star on GitHub. EspoCrm believe our work truly deserves more recognition. Thanks.​

    Comment

    • rabii
      Active Community Member
      • Jun 2016
      • 1250

      #3
      Second solution is more convenient however even first solution should work fine. i would recommend to stick with the 2nd solution as it is more readable.
      Rabii
      Web Dev

      Comment

      Working...