Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save an object when you do not know if its parent objects exist or not?
    primarykey
    data
    text
    <p>I have three tables,</p> <pre><code>Business: id name Office: id name business_id Employee: id name office_id </code></pre> <p>Employee's have office_id as a foreign key and Offices have business_id as a foreign key.</p> <p>I have a domain object/entity that relates to each and a database mapper object that relates to each.</p> <p>Now how to insert a new Employee when I am provided by a Business name, Office name and Employee name?</p> <p>Initially I figure the logic should be something like:</p> <pre><code>$businessMapper = new businessMapper(); $business = $businessMapper-&gt;findBusinessByName($business_name); if ($business == false) { $business = new businessEntity(array( 'businessName' =&gt; $business_name, )); $businessMapper-&gt;save($business); } $officeMapper = new officeMapper(); $office = $officeMapper-&gt;getOfficeByName($office_name, $business); .......etc....... </code></pre> <p>But then I realised that if I have to save a new business there is no way that I have an office or an employee so it is a wasted query to try to get them. So then I thought I should create an if/else stucture.</p> <pre><code>get business entity by business_name if ($business == false) { create business entity save business entity create office entity save office entity create employee entity save employee entity } else { get office entity by office_name + business_id if (office == false) { create office entity save office entity create employee entity save employee entity } else { ......etc...... } } </code></pre> <p>But there is so much duplicated logic and it is very unscaleable/dirty.</p> <p>So how should it be achieved?</p> <p>And secondly where should the logic go? Should it go in the mapper of employee? or the controller for the 'Add employee' action or should it have a new model?</p> <p>I am using Zend as my framework, but I think the question applies to all MVC style structures so please feel free to respond regardless of your framework preference :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload