如何解决Laravel updateOrCreate做一些条件
我具有通过updateOrCreate使用laravel livewire的功能,但是我具有循环编号的功能,并且其make update具有错误的值。那么如何知道这个输入是更新还是创建呢?以及如何用其他方式操纵它?就像它是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;
}
解决方法
使用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();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。