duanduo3712 2019-01-16 02:44
浏览 71
已采纳

Laravel Eloquent Eager从多个表中加载

I'm relatively new to Laravel and only recently started to learn about eager loading. 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:

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

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. Partner B is still considered not connected to A.

  • 写回答

1条回答 默认 最新

  • douwu5009 2019-01-16 08:41
    关注

    I am not sure exactly which model do you want to eager load (i.e. model_type or connect_type), but in either case you can use a morphTo relation, as in:

    public function following()
        {
            return $this->morphTo(null, $type = 'connect_type', $id = 'connect_to');
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥70 刚刚看到一个人的网站居然是通过cname访问的
  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录