簡體   English   中英

Laravel和MySQL是否可以不存在插入記錄,不存在刪除記錄?

[英]Is it possible to insert records if not exists and delete records if not provided in Laravel and MySQL?

我的 Laravel 視圖中有幾個復選框可以說:

<input type="check" name="John">
<input type="check" name="Jane">
<input type="check" name="Mae">
<input type="check" name="Peter">

當我選中所有復選框時,它將像這樣保存在數據庫中:

#Participants Table
_____________
id  |  name
----+--------
 1  |  John
 2  |  jane
 3  |  Mae
 4  |  Peter

在我的日志表中:

#Log Table
_________________
id  |  activity
----+------------
 1  |  Added John as participant
 2  |  Added jane as participant
 3  |  Added Mae as participant
 4  |  Added Peter as participant

現在,我的問題是更新participants時。; 在我的 Laravel 視圖中,我根據參與者表數據選中了所有復選框,假設我取消選中JohnPeter ,單擊更新時如何在我的日志表中添加如下顯示的歷史記錄:

#Log Table
_________________
id  |  activity
----+------------
 1  |  Added John as participant
 2  |  Added jane as participant
 3  |  Added Mae as participant
 4  |  Added Peter as participant
 5  |  Removed John as participant
 6  |  Removed Peter as participant

然后在我的參與者表中

#Participants Table
_____________
id  |  name
----+--------
 2  |  jane
 3  |  Mae

到目前為止我在更新上做了什么:

$members = json_decode($request->projectmembers);
foreach ($members as $participantsitems) {
    DB::beginTransaction();
    DB::table('projects_participants')->upsert([
        'project_id' => $request->projectid,
        'task_id' => "",
        'emp_number' => $participantsitems->id,
        'created_by' => Auth::user()->emp_number,
        'date_created' => Carbon::parse(Carbon::now()),
    ],
    [
        'project_id' => $request->projectid, 
        'emp_number' => $participantsitems->id,
    ]);
    DB::commit();
    $this->record_project_history("Added ".$participantsitems->name ." as participant",$request->projectid, "");
}

但它所做的是,如果記錄不存在則插入,如果記錄存在則更新。 誰能給我一個關於如何解決我的問題的想法? 謝謝!

沒有直接的原因要這樣做。 你應該自己做這個邏輯。

但是你有一些工作人員可以幫助你(附加到你方法這個片段):

// after update/insert your new data you will need to delete other records
// using updated_at column to delete all records updated a second ago
// make sure to create a model for projects_participants and use it all over your code
ProjectsParticipant::where('project_id', $request->projectid)
->where('updated_at', '<=', Carbon::now()->subSecond())->delete();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM