[英]Laravel Getting value of another table using foreign key on Blade
我有兩個模型 Batch 和 Notices。 外鍵格式正確,數據保存在數據庫中。 現在我無法在列表刀片上顯示數據。
注意遷移:
Schema::create('notices', function (Blueprint $table) {
$table->id();
$table->string('noticeTitle');
$table->string('noticeDesc');
$table->string('file')->nullable();
$table->unsignedBigInteger('batch_id');
$table->foreign('batch_id')->references('id')->on('batches');
$table->timestamps();
});
批量遷移:
Schema::create('batches', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
來自數據庫的數據轉儲是:
"id" => 1
"noticeTitle" => "Quae ea est temporib"
"noticeDesc" => "<p>sa</p>"
"file" => null
"batch_id" => 2
"created_at" => "2020-07-27 16:09:52"
"updated_at" => "2020-07-27 16:09:52"
]
通知model
public function batches()
{
return $this->belongsTo(Batch::class);
}
批次 Model
public function notice()
{
return $this->hasMany(Notice::class);
}
公告controller
public function index(){
$notices = Notice::all();
return view('admin.notice.list')
->with('notices', $notices);
}
public function store(Request $request)
{
$this->validate($request, [
'noticeTitle' => 'required',
'noticeDesc' => 'required',
]);
$notice = new Notice;
$notice->noticeTitle = $request->input('noticeTitle');
$notice->noticeDesc = $request->input('noticeDesc');
$notice->batch_id = $request->input('targetedGroup');
if($request->hasFile('file')) {
$noticeTitle = $request->input('noticeTitle');
$filename = $request->file->getClientOriginalName();
$request->file->storeAs('public/noticeFile/additionalFiles', $noticeTitle.'_'.$filename);
$path = $noticeTitle.'_'.$filename;
$notice->file = $path;
}
try{
$notice->save();
Session::flash('success', 'Notice Saved');
return redirect()->route('notice.index');
}
catch (\Throwable $th){
Session::flash('danger', 'Something went wrong');
return redirect()->route('notice.index');
}
}
現在我想從 batch_id 獲取批次名稱
首先,您可能想要更改關系的 function 名稱。 你的通知只有一個批次,所以它應該是public function batch()
而一個批次有幾個通知,所以public function notices()
。 您可以像訪問任何屬性一樣訪問您的關系,因此在您的刀片中:
@foreach($notices as $notice)
@php $batch = $notice->batch; @endphp
{{$batch->name}}
@endforeach
甚至更短(如果您不打算將相關批次用於其他用途)
@foreach($notices as $notice)
{{$notice->batch->name}}
@endforeach
這一切都在 Laravel 文檔中進行了解釋: https://laravel.com/docs/7.x/eloquent-relationships
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.