【问题标题】:Multiple level hasManyThrough relationship with Eloquent多级 hasManyThrough 与 Eloquent 的关系
【发布时间】:2015-07-22 19:59:22
【问题描述】:

我在我的 PHP 应用程序中使用 Eloquent 并在 hasManyThrough 关系中苦苦挣扎。

这是我的结构:

Company 
   id
   name

Admin
   id
   company_id
   name

Offer
   id
   admin_id
   name

Application
   id
   offer_id
   candidat_id

每个Admin 都是Company 的一部分,并且可以发布Offer,候选人可以在该优惠上提供Application

我正在尝试获取所有针对该公司管理员已启动的优惠提出的申请。

我尝试在我的Company 模型中使用hasManyThrough 关系,如下所示:

public function applications()
{
    return $this->hasManyThrough("Application", "Offer");
}

但我收到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'offers.entreprise_id' in 'field list' (SQL: select `applications`.*, `offers`.`entreprise_id` from `applications` inner join `offers` on `offers`.`id` = `applications`.`offer_id` where `offers`.`entreprise_id` in (1))

这是有道理的,因为它认为Offer 被列为Company 而不是Admin

如何设置它以便它查找该公司的Admin,而不必获取该公司的所有管理员然后循环遍历它们,获取每个管理员的所有应用程序?

这可行,但当 Eloquent 提供这些关系让我们的生活更轻松时,这似乎是一种乏味的方式。有没有更优雅的方式来实现我想要的?

【问题讨论】:

标签: php eloquent relationship


【解决方案1】:

这种情况下没有原生关系。

我创建了一个无限级别的HasManyThrough 关系:Repository on GitHub

安装后可以这样使用:

class Company extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function applications() {
        return $this->hasManyDeep(Application::class, [Admin::class, Offer::class]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-26
    • 2020-10-14
    • 2020-02-02
    • 1970-01-01
    • 2016-09-26
    • 2018-11-28
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多