Announcement

Collapse
No announcement yet.

Insert new record with a relationship link

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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

  • #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.

    Comment


    • #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.

      Comment

      Working...
      X