【发布时间】:2015-03-21 06:37:23
【问题描述】:
架构: 媒体: ID, mediable_id, mediable_type, 名字
类别 ID, parent_id, 姓名,
文章 ID, 标题, 描述, author_id 和其他一些元数据字段
articles_categories article_id, 类别ID,
用户 ID, 姓名, 电子邮件, 通过
关系:
文章和类别:多对多
文章和媒体:多态一对多
- 类别到媒体:多态一对多
- 给用户的文章:一对一
我尝试了 damiani 在Laravel - Eager Loading Polymorphic Relation's Related Models 建议的各种方法,但不知何故,我无法为文章和类别急切加载媒体。
$articles = Categories->with(array('user', 'media','articles' => function($query)
{
$query->where('articles.is_featured', '=', 1)
->where('articles.status', '=', 1)
->where('published_at', '>=', new \DateTime('today'))
->orderBy('created_at', 'desc');
}));
我也试过: $articles = Categories->with('articles', 'articles.media', 'articles.user');
【问题讨论】:
-
只需将
articles.media添加到with数组即可。 -
我已经尝试过了,但没有运气。
-
定义
with no luck。如果您不告诉我们您尝试了什么以及输出与您预期的输出相比,我们很难为您提供帮助。 -
谢谢贾雷克!我阅读了更多关于它的内容并找到了预期的结果。代码没有问题,但我对 JOIN 和 Eager 加载的对象感到困惑。我只是在调试 SQL 输出以查看是否引用了媒体表,但显然这是错误的方法。我在 $categories 的
foreach循环中获取文章对象,而要获取与文章相关的媒体,我必须遍历$articles->media as $medias。