【问题标题】:Laravel updateOrCreate make some conditionLaravel updateOrCreate 做一些条件
【发布时间】:2021-01-21 23:10:45
【问题描述】:

我有使用 laravel livewire 使用 updateOrCreate 的功能,但我有循环数字的功能,它的 make update 有错误的值。那么如何知道这个输入是更新还是创建呢?以及如何使用 if else 来操纵它?比如如果它的 create .... ,或者 elseif update ....

这是我的功能

public function store_uraian()
{
    $data = $this->anggaran ;
    $kode = $this->k_koderek ;
    $anggaran = str_replace(".", "", $data);
    $first = UraianKegiatan::all()->count();
  

    if ($first < 9) {
        $new = sprintf("0%d", $first + 1);
    } else {
        $new = $first + 1;
    }

    UraianKegiatan::updateOrCreate(['id' => $this->uraiankegiatanid],[
        'uraian_id' => $this->newid, 
        'kode_rekening' => $kode.'.'.$new, // on here i have problem
        'uraian' => $this->uraian ,
        'anggaran' => $anggaran ,
    ]);

    $this->hideModal();

    $this->emit('alert', ['type' => 'success', 'message' =>'Succes Melakukan Input / Update']);
}

我的问题在线 'kode_rekening' => $kode.'.'.$new, // 在这里我有问题

如果我确实创建了函数,它的正常和工作,但如果更新它的值是错误的。如何检测这是正在创建还是正在更新行?以及如何使条件像

if (create) {
    'kode_rekening' => $kode.'.'.$new,
} else {
    'kode_rekening' =>  $this->kode_rekening;
}

【问题讨论】:

    标签: laravel eloquent laravel-livewire


    【解决方案1】:

    当您使用updateOrCreate() 并传递您想要有条件地设置的值时,您无法知道该值是否正在更新或插入。您需要先尝试获取实际实例,然后才能检查它是否存在。

    相反,我们将使用firstOrNew(),并检查结果对象上的属性exists。如果没有,我们设置kode_rekening 属性并保存。

    // Create or find the object
    $kegiatan = UraianKegiatan::firstOrNew([
            'id' => $this->uraiankegiatanid
        ], [
            'uraian_id' => $this->newid, 
            'uraian' => $this->uraian ,
            'anggaran' => $anggaran ,
        ]);
    
    // If the property does not exists, specify the kode_rekening attribute and save it
    if (!$kegiatan->exists) {
        $kegiatan->kode_rekening = $kode.'.'.$new;
    }
    
    // If any values was changed, or the object was recently created, save it
    if ($kegiatan->isDirty()) {
        $kegiatan->save(); 
    }
    

    【讨论】:

    • 等我试试
    • 它有错误,所有数据都没有传入数据库
    • 然后您需要检查您的数据开始通过(以及可填充属性)。上面的代码与您答案中的代码几乎完全相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2021-09-24
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-07
    • 2018-10-08
    相关资源
    最近更新 更多