【发布时间】:2016-03-17 05:23:27
【问题描述】:
我正在努力了解 Laravel 的关系,但对我要实现的最后一部分有困难。
我的桌子是这样的:
页面模板
id
页面
id
pagetemplate_id
pagetemplate_blocks
id
pagetemplate_id
pagetemplateblocks_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 实例,这对于所有页面都是相同的。虽然每个 Page 应该有不同的 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 建议创建的“pagetemplateblockcontent”。
【问题讨论】:
-
您的查询/获取数据的方式是什么?
-
我正在使用
$this->pageRepo->where('id', $id)->with('pageTemplate'); -
$this->pageRepo是什么,请将完整方法添加到您的问题中 -
它不是一个方法,它实例化一个 eloquent 存储库,以便我可以访问 eloquent 方法(where、with 等)
标签: php laravel eloquent relationship laravel-5.1