Laravel Eloquent 与不同外键的关系

Laravel 版本是 7.0:


我已经设置了这样的模型关系。


<?php


namespace App;



class Template extends Model

{


    protected $fillable = ['header_id', 'content', 'name'];


    public function header()

    {

        return $this->belongsTo('App\Header', 'header_id');

    }

}

在控制器中,我可以获取带有标题的模板对象。


<?php


namespace App\Http\Controllers;

use App\Template;


class TemplateController extends Controller

{


   public function show($id)

   {

     $template = Template::find($id);

   }

}

现在我可以$template->header在视图中使用了。


如何传递不同的 header_id 并获取标头关系对象?我想这样做:


<?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;

   }

}

我想在视图中获得新的标题关系:


当我在视图中执行操作时,有什么方法可以返回新的标头关系$template->header。


谢谢


ABOUTYOU
浏览 89回答 1
1回答

湖上湖

是的,您可以做您想做的事情,但有点破坏数据库中的关系。您可以分配任何 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');&nbsp;$template->header; // should be header with id = 897
打开App,查看更多内容
随时随地看视频慕课网APP