我正在嘗試在視圖中列印 {{$day->date}} 。該屬性僅回傳年份YYYY而不是完整日期YYYY-MM-DD。
誰能解釋我為什么它會這樣作業?以及如何從酒店獲得完整日期?
守則_
@foreach($calendar as $day)
{{dd($day->date)}}
<br>
@endforeach
預期產出
2022-03-01
2022-03-02
...
...
實際輸出
2022
2022
...
...
視圖中的屬性$day:使用{{dd($day)}}刀片
#attributes: array:4 [▼
"date" => "2022-03-01"
"day" => "Tuesday"
"note" => "Public Holiday - Maha Sivarathri"
"is_working_day" => 0
]
{{dd($day->date)}}視圖中的輸出
2022
控制器_
$calendar = Calendar::wherebetween('date',[$date_from,$date_to])->get();
$data['calendar']=$calendar;
return view('cms.advanceprogram.calendar')->with($data);
Calendar.php模型_
class Calendar extends Model{
use HasFactory;
protected $primaryKey = 'date';
public function advanceprograms(){
return $this->belongsToMany(AdvanceProgram::class, 'advance_program_calendar', 'date', 'advance_program_id');
}
}
遷移_
Schema::create('calendars', function (Blueprint $table) {
$table->date('date')->primary();
$table->string('day');
$table->string('note')->nullable();
$table->boolean('is_working_day');
});
uj5u.com熱心網友回復:
我認為,您不應該使用日期作為主鍵。為主鍵添加列id。
Laravel 將主鍵轉換為整數。在模型中替換或洗掉protected $primaryKey,您將在 Blade 中得到正確的結果。
模型Calendar
class Calendar extends Model
{
use HasFactory;
public function advanceprograms(){
return $this->belongsToMany(AdvanceProgram::class, 'advance_program_calendar', 'date', 'advance_program_id');
}
}
看法
@foreach($calendar as $day)
{{$day->date}}
<br>
@endforeach
結果:
2022-03-01
要么
添加到Calendar一行protected $keyType = 'string';
像這樣:
class Calendar extends Model
{
use HasFactory;
protected $primaryKey = 'date';
protected $keyType = 'string';
public function advanceprograms(){
return $this->belongsToMany(AdvanceProgram::class, 'advance_program_calendar', 'date', 'advance_program_id');
}
}
要么
添加到Calendar一行protected $keyType = 'date';
然后欄位date將是一個Carbon類的實體。像這樣:
class Calendar extends Model
{
use HasFactory;
protected $primaryKey = 'date';
protected $keyType = 'date';
public function advanceprograms(){
return $this->belongsToMany(AdvanceProgram::class, 'advance_program_calendar', 'date', 'advance_program_id');
}
}
然后你可以在視圖中使用 Carbon 方法。像這樣:
@foreach($calendar as $day)
{{$day->date->format('d-m-Y')}}
<br>
@endforeach
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430643.html
標籤:php 拉拉维尔 雄辩 laravel-刀片
