为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 83 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信