我在 App\Models 中的模型,我添加了 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 show($company_id, $year) {
$master_cuti = CompanyMasterCuti::where('company_id', $request->company_id)->where('year', $request->year)->first();
return view('master-cuti.show', compact('master_cuti'));
}
我在 index.blade.php 中的代码指向路由显示
@forelse($master_cuti as $m_cuti)
<a href="{{ route('master-cuti.show', [$m_cuti->company_id, $m_cuti->year] ) }}">
<i class="badge-circle badge-circle-light-secondary bx bxs-show font-medium-1 text-success"></i>
</a>
@endforelse
我在 show.blade.php 中的代码
<div class="card-content">
<div class="card-body">
<ul class="list-group p-2" style="padding-top: 5px !important">
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="mr-3">Tahun</span>
<span>{{ $master_cuti->year }}</span>
</li>
<li class="list-group-item d-flex justify-content-between align-items-center">
<span class="mr-3">Cuti</span>
<span>{{ $master_cuti->cuti}}</span>
</li>
</ul>
</div>
</div>
路线
Route::resource('master-cuti', CompanyMasterCutiController::class);
我想显示基于 company_id 和 year 的数据,这是 table company_master_cuti 的主键。我的代码不正确,因为我试图从控制器返回数据,但数据为空,我的代码有什么问题?我的问题有什么解决方案吗?
Laravel 不支持复合主键,请在此处查看。如果您想要一个复合主键,您需要手动完成所有工作。
我建议将其id
作为主键,并将company_id, year
对定义为unique
键。
您仍然可以忽略id
作为主键并使用company_id, year
对作为主键,但正如我提到的那样,这将是手动工作。检查路由和控制器更改。
Route::get('master-cuti/{company_id}/{year}/show', CompanyMasterCutiController::class)->name('master-cuti.show');
public function show($company_id, $year) {
$master_cuti = CompanyMasterCuti::where('company_id', $company_id)->where('year', $year)->first();
return view('master-cuti.show', compact('master_cuti'));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句