2016-04-22 57 views
0

我们公司正在创建(非常活跃)注册表格。处理这些数据的应用程序是Laravel 5应用程序。我正试图消除注册处理脚本中的所有不必要的查询。但是请注意,它是甚至更​​重要我们正确记录每个注册。

现在,我写了这个到应用程序流:

$entry_timestamp = time(); 

DB::table('form_registration_data')->insert($userDataArray); 

$matchArray = array('last_name' => $last_name, 'entry_timestamp' => $entry_timestamp);// the (required field last_name/unix entry_timestamp) pair is (safely IMO) assumed to be a unique "ID" 

$sql = DB::table('form_registration_data')->select('entry_id')->where($matchArray)->first(); 

if (!empty($sql)) { 
    //from this point script knows user data was recorded properly 
} else { 
    $errorMsg = 'There was a problem with the server. Please try again."; 
} 

我之所以写了一个单独的选择查询我不是100%一定的,只是因为插入查询没有失败这个手段它正确执行和数据被正确地记录在DB(请记住,这是最重要的方面)

换句话说,这就是为什么我没有写这样的剧本:

$sql = DB::table('form_registration_data')->insert($userDataArray); 

if ($sql) { 
    //was the data truly recorded properly - 100% guaranteed ??? 
} else { 
    $errorMsg = 'There was a problem with the server. Please try again."; 
} 

我太过分了吗?换句话说,插入查询GUARANTEE的非失败是否在DB中记录了正确的数据?

+1

为什么不尝试获取它的基础上'LAST_INSERT_ID()',看看它是否在那里,以确保?如果它没有失败它可能成功了,但是不能保证别的东西没有删除它,或者将来不会删除它。编程充满了不确定性。 – tadman

+0

同意,如果您使用ORM并为该变量分配要保存的值。您可以使用$ data-> id来检查保存。如果id不在那里,它不会保存。 – arcee123

+0

@tadman真实 - 但问题集中在脚本执行的时候 - 而不是未来的删除。该脚本的其他部分没有任何删除功能 –

回答

0

这将工作。您还可以使用$数据 - > id来引用联接表作为外键插入:

// In your models file, this will set table. 
class Registration extends Model { 

    protected $FIELD1; 
    protected $FIELD2; 
    protected $FIELD3; 
    protected $FIELD4; 
    protected $FIELD5; 
    protected $FIELD6; 
    protected $FIELD7; 
} 


//In your controller: 

$data = new Registration(); 

$data->FIELD1 = VALUE1; 
$data->FIELD2 = VALUE2; 
$data->FIELD3 = VALUE3; 
$data->FIELD4 = VALUE4; 
$data->FIELD5 = VALUE5; 
$data->FIELD6 = VALUE6; 

if($data->save()) { 
    echo 'ID: ' & $data->id & ' Saved.' 
} 
+0

谢谢你的回答。每个注册表格的字段数量可能会有很大不同,并且可以随时由表单的作者更改。性能也很重要,加入巨大的表来检查外键是不是我想要做的事情。看到我最后一个评论IMO更简单的“中间地带”方法 –

+1

好的。看看这个:http://laravel.io/forum/04-30-2014-saving-dynamically-created-form-field-array-to-db-laravel-way – arcee123

相关问题