【问题标题】:Update where not exists except row's updating, using Illuminate database使用 Illuminate 数据库更新除行更新外不存在的地方
【发布时间】:2016-11-11 03:20:00
【问题描述】:

我想更新记录并检查表中是否不存在,但问题是如果我检查存在,它可以工作,但我什至无法更新我选择的一条记录,因为它已经存在。

这是我的代码

$app->post('/update_function', function($request, $response, $args) {
$exists = $this->db->table('functions')->where('project_id', '=', $request->getParam('project_id'))
                                       ->where('function_number', '=', $request->getParam('function_number'))
                                       ->exists();

if(!$exists) {
    $query = $this->db->table('functions')
                  ->where('function_id', '=', $request->getParam('function_id'))
                  ->update([
                    'project_id' => $request->getParam('project_id'),
                    'function_number' => $request->getParam('function_number'),
                    'function_text' => $request->getParam('function_text')
                  ]);
    if($query) {
         echo "Function was updated";
    }
}else {
    echo "Can not update duplicate function number";
}                         
});

【问题讨论】:

  • 基本上相当于“修复我的代码”的问题需要解决。请尝试将您的代码缩小到最低限度的完整可验证示例。

标签: mysql slim query-builder illuminate-container


【解决方案1】:

简单的解决方案

不要使用exists,使用first()

$record = $this->db->table('functions')
                   ->where('project_id', '=', $request->getParam('project_id'))
                   ->where('function_number', '=', $request->getParam('function_number'))
                   ->first();
if (is_null($record)) { //record does not exist }
else { 
    $record->update([
         'project_id' => $request->getParam('project_id'),
         'function_number' => $request->getParam('function_number'),
         'function_text' => $request->getParam('function_text')
    ]);
    $record->save();
}

这假设您只提取一条记录...如果不是,则只需使用 for each 通过将 first 替换为 get 来迭代所有记录。

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2017-03-04
    • 1970-01-01
    相关资源
    最近更新 更多