php - 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
在视图中时,有什么方法可以返回新的标题关系。
谢谢
解决方案
是的,你可以做你想做的事,但有点破坏了数据库中的关系。您可以将任何 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
推荐阅读
- ionic-framework - 无法使用 Firebase 插件创建构建
- bash - 即使作为 root 用户也无法使用 chown 更改所有权
- laravel - 如何处理导致记录数量越来越少的多个更新
- c - 如何隐藏linux静态库的本地符号
- json - 将Json内容组合并加载为python字典
- java - 通过按钮等待时间读取大型 txt 文件
- linux - 如何使用 python 在亚马逊 s3 存储桶中获取 csv 文件名?
- django - Django 中的自定义 ORM。基于实体 ID 和实体类型
- javascript - 设置后如何直接渲染状态?
- python - 当没有activate.bat并且我是凡人时,如何在虚拟环境中的任务调度程序中运行python脚本