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

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

web.php中的我的路由

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

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

class CompanyMasterCuti extends Model
{
    use HasFactory;

    protected $table = 'company_master_cuti';
    protected $fillable = [
        'company_id', 'year', 'cuti', 'created', 'created_by', 'modified', 'modified_by', 
    ];
    protected $guarded = [];
    protected $keyType = 'string';
    public $timestamps = false;
    protected $primaryKey = ['company_id', 'year'];
    public $incrementing = false;

    public function company() {
        return $this->belongsTo('App\Models\Company', 'company_id', 'id');
    }
}

我的控制器代码

public function delete_master_cuti(Request $request) {

        $master_cuti = CompanyMasterCuti::where($request->company_id)->where($request->year);
        $master_cuti->delete();

        toast('Successfull', 'success');
        return redirect()->route('master-cuti.index');

    }


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

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

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

<form id="form-edit" action="{{ route('delete_master_cuti') }}" method="POST">
                        @csrf
                        <div class="modal-body">
                            <input type="hidden" id="master_cuti_ids" name="company_id">
                            <div class="row no-gutters">

                                <div class="col-md-6">
                                    <button type="submit" class="btn btn-danger ml-1" style="width: 100%">
                                        <i class="bx bx-check d-block d-sm-none"></i>
                                        <span class="d-none d-sm-block">Delete</span>
                                    </button>
                                </div>
                            </div>

                        </div>
                    </form>

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

jdgnovmf

jdgnovmf1#

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

protected function setKeysForSaveQuery($query)
    {
        $query
            ->where('company_id', '=', $this->getAttribute('company_id'))
            ->where('year', '=', $this->getAttribute('year'));

        return $query;
    }

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

相关问题