首页 > 解决方案 > 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在视图中时,有什么方法可以返回新的标题关系。

谢谢

标签: phplaravellaravel-5eloquenteloquent-relationship

解决方案


是的,你可以做你想做的事,但有点破坏了数据库中的关系。您可以将任何 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

推荐阅读