简体   繁体   English

Laravel雄辩的渴望从多个表加载

[英]Laravel Eloquent Eager Load from Multiple Table

I'm relatively new to Laravel and only recently started to learn about eager loading. 我是Laravel的新手,直到最近才开始学习热切的加载。 Currently, I have a project in which I was required to develop an app for connection between companies and partners. 目前,我有一个项目,要求我开发一个用于在公司和合作伙伴之间建立联系的应用程序。

Connection can either be between company-company, partner-partner or company-partner. 连接可以在公司-公司,合作伙伴-伙伴或公司-伙伴之间。 For now, I stored all the connections in one Connection table as shown here : 现在,我存储的所有连接在一个接线表所示在这里

In Connection class, I use polymorphic to retrieve all the connections for a company/partner: Connection类中,我使用多态来检索公司/合作伙伴的所有连接:

public function connectable()
{
    return $this->morphTo();
}

And this function in Partner and Company classes: 合作伙伴公司类中的此功能:

public function my_connection()
{
    return $this->morphMany(Connection::class, 'connectable', 'model_type', 'model_id');
}

I can retrieve the list of connections just fine, but problem arise when I want to get the details for each connected company/partner. 我可以很好地检索连接列表,但是当我想获取每个连接的公司/合作伙伴的详细信息时会出现问题。 I want to use eager load in Connection class as below but it only manage to either get from company or partner but not both 我想在Connection类中使用如下所示的紧急负载,但它只能从公司或合作伙伴处获取,而不能同时从两者处获取

protected $with = [
    'following'
];

public function following()
{
    return $this->belongsTo(Company::class, 'connect_to', 'id');
}

Is it possible to do this? 是否有可能做到这一点? Or should I separate company and partner connections into different tables? 还是应该将公司和合作伙伴的连接分成不同的表?

Edit : By connection, I meant a partner or company can connect/follow each other like the usual social media app. 编辑 :通过连接,我的意思是合作伙伴或公司可以像通常的社交媒体应用程序那样彼此连接/关注。 It wasn't mutual tho. 这不是相互的。 Say, if Partner A follow Partner B, then only that connection will be stored. 假设,如果合作伙伴A跟随合作伙伴B,那么将仅存储该连接。 Partner B is still considered not connected to A. 仍认为伙伴B未连接到A。

I am not sure exactly which model do you want to eager load (ie model_type or connect_type ), but in either case you can use a morphTo relation, as in: 我不确定要加载哪个模型(即model_typeconnect_type ),但是无论哪种情况,都可以使用morphTo关系,如下所示:

public function following()
    {
        return $this->morphTo(null, $type = 'connect_type', $id = 'connect_to');
    }

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

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