【问题标题】:Laravel Eloquent Relationship with different foreign keyLaravel Eloquent 与不同外键的关系
【发布时间】:2020-10-20 20:54:52
【问题描述】:

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-&gt;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-&gt;header 时,有什么方法可以返回新的标题关系。

谢谢

【问题讨论】:

    标签: php laravel laravel-5 eloquent eloquent-relationship


    【解决方案1】:

    是的,你可以做你想做的事,但有点破坏了数据库中的关系。您可以将任何 id 分配给 $template-&gt;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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 1970-01-01
      • 2020-12-16
      • 2021-07-05
      • 2021-10-29
      • 2016-11-21
      • 2020-04-20
      相关资源
      最近更新 更多