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
时,有没有方法返回新的头关系。
谢谢
是的,你可以做你想做的事情,但这有点儿破坏了数据库中的关系。 您可以将任意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