HasManyThrough 一对多关系 [英] HasManyThrough with one-to-many relationship
本文介绍了HasManyThrough 一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为一个带有如下表格的项目开发小型 CMS:
I am working on small scale CMS for a project with tables like so:
- pages
- id
…
- translations
- page_id
…
- menus
- id
…
- menu_page
- menu_id
- page_id
…
在菜单模型中,我有这种关系:
In the Menu model I have this relationship:
function pages(){
return $this->hasMany('Page');
}
是否可以直接在 Menu 和 Translations 之间创建一种关系,以转换为类似于此 SQL 查询的内容:
Is it possible to create a relation directly between Menu and Translations that translates to something like this SQL query:
select translations.*
from translations
inner join menu_page on menu_page.page_id = translations.page_id
where menu_page.menu_id = ?;
谢谢!
推荐答案
你不能用内置方法做到这一点,hasManyThrough
不适用于多对多关系菜单页面.
You can't do it with builtin methods, hasManyThrough
won't work with many-to-many relation menus-pages.
不过,您可以尝试以下解决方法:
However you can try a workaround like this:
public function getTranslationsAttribute()
{
if ( ! array_key_exists('translations', $this->relations)) $this->loadTranslations();
return $this->getRelation('translations');
}
protected function loadTranslations()
{
$translations = Translation::join('menu_page', 'translations.page_id', '=', 'menu_page.page_id')
->where('menu_page.menu_id', $this->getKey())
->distinct()
->get(['translations.*','menu_id']);
$hasMany = new IlluminateDatabaseEloquentRelationsHasMany(Translation::query(), $this, 'menu_id', 'id');
$hasMany->matchMany(array($this), $translations, 'translations');
return $this;
}
现在你可以这样做:
$menu = Menu::find($id);
$menu->translations; // Eloquent Collection of Translation models
所以基本上就像您使用任何关系一样.唯一的问题是你不能急切加载它.
So basically just like you would use any relation. The only trouble is that you can't eager load it.
这篇关于HasManyThrough 一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文