Php 当您不知道某个对象的父对象是否存在时,如何保存该对象?

Php 当您不知道某个对象的父对象是否存在时,如何保存该对象?,php,model-view-controller,zend-framework,model,datamapper,Php,Model View Controller,Zend Framework,Model,Datamapper,我有三张桌子 Business: id name Office: id name business_id Employee: id name office_id 员工的办公室id作为外键,办公室id作为外键 我有一个与每个相关的域对象/实体和一个与每个相关的数据库映射器对象 现在,如果提供了企业名称、办公室名称和员工姓名,如何插入新员工 最初我认为逻辑应该是这样的: $businessMapper = new businessMapper(); $busin

我有三张桌子

Business:
  id
  name
Office:
  id
  name
  business_id
Employee:
  id
  name
  office_id
员工的办公室id作为外键,办公室id作为外键

我有一个与每个相关的域对象/实体和一个与每个相关的数据库映射器对象

现在,如果提供了企业名称、办公室名称和员工姓名,如何插入新员工

最初我认为逻辑应该是这样的:

$businessMapper = new businessMapper();  
$business = $businessMapper->findBusinessByName($business_name);

if ($business == false) {   
     $business = new businessEntity(array(         
                     'businessName' => $business_name,            
                   ));        
     $businessMapper->save($business);   
  } 

 $officeMapper = new officeMapper();     
 $office = $officeMapper->getOfficeByName($office_name, $business);

.......etc.......
但后来我意识到,如果我必须拯救一家新企业,我就不可能拥有一个办公室或一名员工,因此试图获得他们是一种浪费。所以我想我应该创建一个if/else结构

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......
   }

}
但是有太多重复的逻辑,它是非常不可缩放/肮脏的

那么应该如何实现呢

第二,逻辑应该走向何方?它应该放在员工的地图上吗?或“添加员工”操作的控制器,或是否应具有新模型


我正在使用Zend作为我的框架,但我认为这个问题适用于所有MVC风格的结构,因此无论您的框架偏好如何,请随时回答:)

如果您在If()期间使用OR语句块并将查询放在if语句中,那么只有在if语句的第一部分失败时才会执行查询-确保不会不必要地执行查询。就个人而言,我们做了一些类似的事情,但当我们创建一个新域时,我们在域new=1中设置了一个标志,我们改为检查这个标志,相同的方法只是消除了对这些脏变量的需要;-)


这是一个好问题,但我不相信这与MVC有任何关系。此外,它更多地是关于数据映射器的。真的很高兴看到一个问题,有人没有把他们的应用程序敲入可怕的ORM反模式。所以这是+1。
$businessMapper = Factory::getMapper('business');

if (!$business = $businessMapper->findByName("Business Name"))
{
    $business = $businessMapper->create();
    $business->setName("Business Name");
    $businessMapper->save($business);

    $newBusiness = true;
}

$officeMapper = Factory::getMapper('office');

if (isset($newBusiness) || !$office = $officeMapper->findByName("Office Name"))
{
    $office = $officeMapper->create();
    $office->setName("Office Name");
    $office->setBusiness($business->getId());
    $officeMapper->save($office);

    $newOffice = true;
}

$employeeMapper = Factory::getMapper('employee');

if (isset($newOffice) || !$employee = $employeeMapper->findByName("Employee"))
{
    $employee = $employeeMapper->create();
    $employee->setName("Employee Name");
    $employee->setOffice($office->getId());

    $employeeMapper->save($employee);
}