Php Laravel与不同外键的雄辩关系
Laravel版本为7.0: 我已经建立了这样的模型关系Php Laravel与不同外键的雄辩关系,php,laravel,laravel-5,eloquent,eloquent-relationship,Php,Laravel,Laravel 5,Eloquent,Eloquent Relationship,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;
class Template extends Model
{
protected $fillable = ['header_id', 'content', 'name'];
public function header()
{
return $this->belongsTo('App\Header', 'header_id');
}
}
我想查看新的标题关系:
当我在视图中执行$template->header
时,是否有任何方法返回新的标题关系
谢谢你是的,你可以做你想做的事,但有点破坏了数据库中的关系。您可以将任何id分配给
$template->header\u 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
<?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 = 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