【问题标题】:Laravel Distant many to many relationshipLaravel 远程多对多关系
【发布时间】:2015-03-21 06:37:23
【问题描述】:

架构媒体: ID, mediable_id, mediable_type, 名字

类别 ID, parent_id, 姓名,

文章 ID, 标题, 描述, author_id 和其他一些元数据字段

articles_categories article_id, 类别ID,

用户 ID, 姓名, 电子邮件, 通过

关系

  1. 文章和类别:多对多

  2. 文章和媒体:多态一对多

  3. 类别到媒体:多态一对多
  4. 给用户的文章:一对一

我尝试了 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

标签: php laravel-4 eloquent


【解决方案1】:

正如 Jarek 和其他 stackoverflow 用户所建议的,我需要在 with 静态调用中包含另一个引用,我的代码是:

$articles = Category::with(array('articles.media','articles' => function($query)
    {
        $query->where('articles.is_featured', '=', 1)
            ->where('articles.status', '=', 1)
            ->where('published_at', '<=', new \DateTime('today'))   
            ->orderBy('created_at', 'desc');

    }));    

这就是我获得所需数据的方式:

foreach($categories as $category){
        echo "<hr>Category Information: ".$category->id."  :  ".$category->name;
        foreach($category->articles as $article){
            echo "--<br>Article ID is: ".$article->id;
            foreach($article->media as $media){
                echo "----<br>Image: ".$media->name;
            }
        }
    }

我希望我使用的是正确的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 2018-01-22
    • 2016-02-26
    • 2016-01-04
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多