Laravel Eloquent 与不同外键的关系

Laravel Eloquent Relationship with different foreign key

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');
    }
}

在控制器中,我可以使用 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 关系:

有什么方法可以 return 新的 header 关系,当我在视图中 $template->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