Laravel 版本是 7.0:我已經設置了這樣的模型關系。<?phpnamespace App;class Template extends Model{ protected $fillable = ['header_id', 'content', 'name']; public function header() { return $this->belongsTo('App\Header', 'header_id'); }}在控制器中,我可以獲取帶有標題的模板對象。<?phpnamespace App\Http\Controllers;use App\Template;class TemplateController extends Controller{ public function show($id) { $template = Template::find($id); }}現在我可以$template->header在視圖中使用了。如何傳遞不同的 header_id 并獲取標頭關系對象?我想這樣做:<?phpnamespace 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; }}我想在視圖中獲得新的標題關系:當我在視圖中執行操作時,有什么方法可以返回新的標頭關系$template->header。謝謝
1 回答

湖上湖
TA貢獻2003條經驗 獲得超2個贊
是的,您可以做您想做的事情,但有點破壞數據庫中的關系。您可以分配任何 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
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報
0/150
提交
取消