php 如何在laravel中删除有2个主键的数据

jdg4fx2g  于 2022-10-30  发布在  PHP
关注(0)|答案(1)|浏览(235)

web.php中的我的路由

  1. Route::post('delete_master_cuti', [CompanyMasterCutiController::class, 'delete_master_cuti'])->name('delete_master_cuti');

我的模型,我已经添加了company_id和year作为主键

  1. class CompanyMasterCuti extends Model
  2. {
  3. use HasFactory;
  4. protected $table = 'company_master_cuti';
  5. protected $fillable = [
  6. 'company_id', 'year', 'cuti', 'created', 'created_by', 'modified', 'modified_by',
  7. ];
  8. protected $guarded = [];
  9. protected $keyType = 'string';
  10. public $timestamps = false;
  11. protected $primaryKey = ['company_id', 'year'];
  12. public $incrementing = false;
  13. public function company() {
  14. return $this->belongsTo('App\Models\Company', 'company_id', 'id');
  15. }
  16. }

我的控制器代码

  1. public function delete_master_cuti(Request $request) {
  2. $master_cuti = CompanyMasterCuti::where($request->company_id)->where($request->year);
  3. $master_cuti->delete();
  4. toast('Successfull', 'success');
  5. return redirect()->route('master-cuti.index');
  6. }


index.blade.php,在这段代码中我只是添加了company_id,我也不知道如何调用年份。

  1. <a href="javascript:void(0)" data-id="{{ $m_cuti->company_id }}" onclick="$('#master_cuti_ids').val($(this).data('company_id')); $('#deleteModalBu').modal('show');">
  2. <i class="badge-circle badge-circle-light-secondary bx bxs-trash font-medium-1 text-danger my-1"></i>
  3. </a>

表单动作来删除函数删除index.blade.php中的数据

  1. <form id="form-edit" action="{{ route('delete_master_cuti') }}" method="POST">
  2. @csrf
  3. <div class="modal-body">
  4. <input type="hidden" id="master_cuti_ids" name="company_id">
  5. <div class="row no-gutters">
  6. <div class="col-md-6">
  7. <button type="submit" class="btn btn-danger ml-1" style="width: 100%">
  8. <i class="bx bx-check d-block d-sm-none"></i>
  9. <span class="d-none d-sm-block">Delete</span>
  10. </button>
  11. </div>
  12. </div>
  13. </div>
  14. </form>

我想删除基于company_id和年份的数据,但现在所有相同的company_id都被删除了,我想根据用户的选择删除数据,而不是所有company_id。我的问题有什么解决方案吗?

jdgnovmf

jdgnovmf1#

有一种解决方法,您应该覆盖Model方法

  1. protected function setKeysForSaveQuery($query)
  2. {
  3. $query
  4. ->where('company_id', '=', $this->getAttribute('company_id'))
  5. ->where('year', '=', $this->getAttribute('year'));
  6. return $query;
  7. }

阅读了很多之后,我发现了这个https://blog.maqe.com/solved-eloquent-doesnt-support-composite-primary-keys-62b740120f
这对我删除像你这样有两个主键的记录很有效。

相关问题