亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel Eloquent 與不同外鍵的關系

Laravel Eloquent 與不同外鍵的關系

PHP
ABOUTYOU 2023-07-08 16:19:49
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


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 148 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號