[英]How to get foreign key name of loaded relationship using laravel eloquent
[英]Laravel Eloquent Relationship with different foreign key
Laravel版本為7.0:
我已經設置了這樣的 model 關系。
<?php
namespace App;
class Template extends Model
{
protected $fillable = ['header_id', 'content', 'name'];
public function header()
{
return $this->belongsTo('App\Header', 'header_id');
}
}
在 controller 中,我可以使用 header 獲得模板 object。
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id)
{
$template = Template::find($id);
}
}
現在我可以在視圖中使用$template->header
了。
如何傳遞不同的 header_id 並獲取 header 關系 object? 我想做如下:
<?php
namespace App\Http\Controllers;
use App\Template;
class TemplateController extends Controller
{
public function show($id, $temp_header_id)
{
$template = Template::find($id);
$template->header_id = $temp_header_id;
}
}
我想在視圖中獲得新的 header 關系:
當我在視圖中執行$template->header
時,有什么方法可以返回新的 header 關系。
謝謝
是的,你可以做你想做的事,但有點破壞了數據庫中的關系。 您可以將任何 id 分配給$template->header_id
,然后使用該新值加載關系:
$template->header_id = 897;
// load the relationship, will use the new value
// just in case the relationship was already loaded we make sure
// to load it again, since we have a different value for the key
$template->load('header');
$template->header; // should be header with id = 897
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.