【问题标题】:How to save an object when you do not know if its parent objects exist or not?当您不知道其父对象是否存在时,如何保存对象?
【发布时间】:2012-07-17 17:09:24
【问题描述】:

我有三张桌子,

Business:
  id
  name
Office:
  id
  name
  business_id
Employee:
  id
  name
  office_id

员工的 office_id 作为外键,办公室的 business_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 样式结构,所以无论您的框架偏好如何,请随时回复 :)

【问题讨论】:

  • 这是一个很好的问题,但我不相信它与 MVC 有任何关系。此外,它更多的是关于数据映射器而不是其他任何东西。真的很高兴看到有人没有将他们的应用程序敲入某种可怕的 ORM 反模式的问题。所以+1。

标签: php model-view-controller zend-framework model datamapper


【解决方案1】:

如果您在 if() 块期间使用 OR 语句并将您的查询放在 if 语句中,那么只有在 IF 语句的第一部分失败时才会执行它 - 确保您不会不必要地执行查询。就个人而言,我们做了类似的事情,但是当我们创建一个新域时,我们在域 new=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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多