首页 > 解决方案 > Laravel hasManyThrough 返回空结果

问题描述

我有 3 个表:ChatsMessagesInvoices

在此处输入图像描述

之前,我收到过这样的聊天发票:

//ChatModel:
public function invoices()
{
    return $this->hasMany(Invoice::class);
}

但是现在我需要获取特定聊天的聊天消息中出现的所有聊天发票。我应该为此使用 hasManyThrough 吗?不幸的是,下一个示例返回一个空结果

//ChatModel:
public function invoices()
{
    return $this->hasManyThrough(Invoice::class, Message::class, 'chat_id', 'id');
}

标签: phplaraveleloquent

解决方案


由于您的消息表中同时有 chat_id 和 invoice_id,您应该只将消息表作为数据透视表!

public function invoices()
{
    return $this->belongsToMany(Invoice::class, 'messages');
}

推荐阅读