拉拉威尔难以捉摸的关系有很多只有一个


Laravel Eloquent Relationship hasMany hasOne

我试图了解Laravel的关系,但在我试图实现的最后一部分遇到了困难。

我的桌子是这样的:

页面模板

id

页面

id
pagetemplate_id

pagetemplate_blocks

id
pagetemplate_id

pagetemplatelocks_content

id
page_id
page_template_block_id

因此,当从数据库中加载页面时,我需要用页面模板、它的块和内容来获取它。

到目前为止,这是我的代码:

Page.php

public function pageTemplate()
{
    return $this->belongsTo('PageTemplate', 'pagetemplate_id')->with('blocks');
}
public function pagetemplateblockcontent()
{
    return $this->belongsToMany('PageTemplateBlockContent', 'pagetemplateblocks_content', 'page_id', 'page_template_block_id')->withTimestamps();
}
public function pagecontent()
{
    return $this->hasMany('PageTemplateBlockContent', 'page_id')->with('pagetemplateblock');
}

PageTemplate.php

public function page()
{
    return $this->hasMany('Page', 'pagetemplate_id');
}    
public function blocks() {
    return $this->hasMany('PageTemplateBlock', 'pagetemplate_id')->orderBy('sort_order', 'asc')->with('blockcontent');
}

PageTemplateBlock.php

public function pagetemplate() {
    return $this->belongsTo('PageTemplate', 'pagetemplate_id');
}
public function blockcontent() {
    return return $this->hasOne('PageTemplateBlockContent');
}

PageTemplateBlockContent.php

public function pagetemplateblock()
{
    return $this->belongsTo('PageTemplateBlock', 'page_template_block_id');
}

然而,问题是content,如果我尝试这样做,它会返回PageTemplateBlockContent的一个实例,这对所有页面都是一样的。尽管每个页面应该有不同的PageTemplateBlockContent。我不知道如何绕过这一点,所以任何想法都将不胜感激。

更新

我的控制器调用

$this->pageRepo->where('id', $id)->with('pageTemplate');

"pageTemplate"返回以下内容:

return $this->belongsTo('PageTemplate', 'pagetemplate_id')->with('blocks');

"blocks"返回以下内容:

return $this->hasMany('PageTemplateBlock', 'pagetemplate_id')->orderBy('sort_order', 'asc')->with('blockcontent');

"blockcontent"返回以下内容:

return $this->hasOne('PageTemplateBlockContent');

因此,这意味着它永远不会达到Joost建议创建的"页面模板锁定内容"。

更改

public function pagetemplateblockcontent()
{
    return $this->belongsToMany('PageTemplateBlockContent', 'pagetemplateblocks_content', 'page_id', 'page_template_block_id')->withTimestamps();
}

public function pagetemplateblockcontent()
{
    return $this->belongsToMany('PageTemplateBlockContent', 'pagetemplateblockscontent_page', 'page_id', 'page_template_block_id')->withTimestamps();
}

并创建一个具有两个主键的表page_pagettemplateblockcontent

$table->integer("page_id")->unsigned();
$table->integer("page_template_block_id")->unsigned();
$table->primary(['page_id', 'page_template_block_id']);