after_relationship_add逻辑钩子更新查询在sugarcrm中不起作用

时间:2014-05-19 09:07:41

标签: sugarcrm

我在案例模块中创建了一个after_relationship_add逻辑钩子,在这个模块中有一个自定义字段用于插入其中一个自定义模块关系数据。钩子被正确调用,一切正常。但是当我在钩子逻辑中更新案例记录时,更新查询不起作用。但是如果我添加一个die();更新查询执行后的语句,记录得到更新。逻辑钩子代码如下:

public function updateData($bean, $event, $arguments){  

    $caseid = $bean->id;
    $dataid = $arguments['related_id'];
    $query = "SELECT name FROM data1_data where id = '" .$dataid. "'";
    $dataresult = $GLOBALS['db']->query($query , false);
    $dataname = "";
    while (($row = $GLOBALS['db']->fetchByAssoc($dataresult )) != null) {
       $dataname = $row['name'];               
    }

    $newQuery = 'UPDATE cases_cstm SET data_c = "'.$dataname.'" where id_c = "'.$caseid.'" ';
    $newResult = $GLOBALS['db']->query($newQuery);   

    /* here when die() statement is added update query executes properly and 
     * after removing die(); statement nothing happens.*/
    die();
}

任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

在SugarCRM中,您几乎不应直接与数据库交互。几乎所有你需要做的事都可以使用SugarBean对象及其扩展来完成。您在这里看到的是一个很好的例子:您的更新正在访问数据库,但之后立即加载的其余SugarCRM更新正在消除它。

我使用SugarBean和BeanFactory重写了你的函数。请注意,需要多少代码,我希望您发现它有效,因为它不会导致额外的更新。

我不确定的是你最后是否真的需要$bean->save();。如果我们在before_save逻辑钩子中它不会被需要,但是我更少使用after_relationship_add,所以这里可能是必要的。

/**
 * @param $bean aCase object
 * @param $event string, or specifically 'after_relationship_add'
 * @param $arguments array
 */
public function updateData($bean, $event, $arguments){  
    /*
     * Instead of loading the data1_data information from the database
     * directly, consider using the SugarBean PHP object, as this is a SugarCRM
     * best practice. 
     * 
     * Note that we return early if the data1_data object cannot be found or
     * if the 'name' value is blank (as that would make the rest of this script
     * useless)
     */
    $data = BeanFactory::getBean('data1_data',$arguments['related_id']);
    if(empty($data->name)) return;
    $dataname = $data->name;

    /*
     * Instead of sending an update query directly to the database, use the 
     * SugarBean objects, one's loaded already in $bean. Saving objects 
     * with the SugarBean objects instead of direct SQL will ensure that 
     * all workflows and logic hooks are executed correctly. Further, 
     * updating with direct SQL *before* a pending update is sent (such as
     * in a logic hook) will likely overwrite whatever update we're making
     * in SQL. 
     */
    $bean->data_c = $dataname;
    $bean->save();

}