简体   繁体   English

Laravel 5.2 Eloquent - 通过多种关系查找所有id

[英]Laravel 5.2 Eloquent - Finding all id's through multiple relationships

So here are my relationships: 所以这是我的关系:

A fund belongs to a planCode 基金属于planCode

A planCode belongs to a planType planCode属于planType

What I need to do is find the fund_id's that are a part of certain plan types. 我需要做的是找到作为某些计划类型一部分的fund_id。 I tried something like this: 我试过这样的事情:

$plans = (new 'App\\PlanType')->with('planCode.fund')->whereIn('code', ['PENS', 'ANN', 'WEL'])->get();

With this I get the three plan codes with their relationships eager loaded. 有了这个,我得到了三个计划代码,他们的关系急切加载。 What I want is a list of all the fund_id's. 我想要的是所有fund_id的列表。 I tried $plans->lists('planCode.fund.fund_id', 'code') but this returns null for the fund_id. 我尝试了$plans->lists('planCode.fund.fund_id', 'code')但这为fund_id返回null。 Any ideas? 有任何想法吗?

So if your relationships are like this - 所以如果你的关系是这样的 -

PlanCode has many Funds PlanCode 有很多 基金

Fund belongs to a PlanCode 基金 属于 PlanCode

PlanType has many PlanCodes PlanType 有许多 PlanCodes

PlanCode belongs to a PlanType PlanCode 属于 PlanType

Then you can add another relationship like this - 然后你可以添加这样的另一种关系 -

PlanType has many Funds through PlanCodes PlanType 通过 PlanCodes 拥有许多 基金

UPDATE UPDATE

After adding a function like this to your PlanType class - 在您的PlanType类中添加这样的函数后 -

public function funds() {
    return $this->hasManyThrough('fund', 'planCode', PT, PC);
}

You can simply access Funds on your PlanType model like this - 您可以像这样访问PlanType模型上的基金 -

$planType->Funds

Take a look at the docs here . 看看这里的文档。

Yep, atefth has it in one. 是的,atefth有一个。 Laravel has a really useful relationship so that you don't have to make repeated queries to the database to get relations of relations. Laravel有一个非常有用的关系,因此您不必重复查询数据库以获得关系关系。 This is the hasManyThrough relationship. 这是hasManyThrough关系。

So here, for example, your planType model has many fund models through the planCode model. 所以在这里,例如,您的planType模型通过 planCode模型有许多基金模型。 Your planType model should contain a funds method that looks like this, where PC is the planCode->id column name in the fund table, and PT is the planType->id column in the planCode table: 您的planType模型应该包含一个看起来像这样的基金方法,其中PC是基金表中的planCode-> id列名,PT是planCode表中的planType-> id列:

public function funds() {
    return $this->hasManyThrough('fund', 'planCode', PT, PC);
}

You may have to fully namespace your models, depending on the structure of your application. 您可能必须完全命名模型,具体取决于应用程序的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM