【问题标题】:Laravel Eloquent - belongs to many throughLaravel Eloquent - 属于许多通过
【发布时间】:2014-07-19 14:08:55
【问题描述】:

我有网站、页面、元素和 element_creators 表,如下所示:

   sites
     id
     ...
   pages
     id
     site_id
     ...
   elements
     id
     page_id
     ...
   element_creators
     id
     element_id
     ...

我能够检索链接到页面的元素创建者

    $this->belongsToMany('ElementCreator', 'elements', 'page_id', 'element_creator_id');

是否有一种简单的方法可以检索特定网站的所有元素创建者(通过其页面)?

谢谢!

【问题讨论】:

  • 这段代码有问题:要么不是belongsToMany 关系页面->创建者(而是 hasManyThrough),要么这些表的架构与您编写的不同。有可能的解决方案取决于此。

标签: php orm laravel eloquent relationships


【解决方案1】:

目前,我将其用作临时解决方案,希望能找到更好的解决方案:

    public function elementCreators()
    {
        $elementCreators = array();
            foreach ($this->pages as $page) {
                foreach ($page->elementCreators as $elementCreator) {
                    $elementCreators[$elementCreator->id] = $elementCreator;
                }
            }
        return \Illuminate\Database\Eloquent\Collection::make($elementCreators);
    }

【讨论】:

    【解决方案2】:

    你可以试试这个:

    $site = Site::with('pages.elementCreators')->find(1); // 1 is id for example
    

    然后你可以使用这个访问所有elementCreators

    $elementCreators = $site->pages->fetch('elementCreators');
    

    【讨论】:

    • 它有效。但是,目前还有其他更简单的方法吗?
    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2023-02-03
    • 2017-02-19
    • 2016-12-20
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多