php - Laravel 与多个表的雄辩关系
问题描述
我有 3 个表,我正在建立这些表的关系,但是我无法实现它。我有 3 个名为Books
, Chapters
&的表Hadith
。Books
有很多章节的数据,有Chapters
很多圣训。
我的数据库结构:
books
id - integer
name - string
bookSlug - string
chapters
id - integer
chapterNumber - string
bookSlug - string
hadith
id - integer
chapterId - integer (it's the chapter id)
book - string (it's the book slug)
Hadith.php - 型号:
class Hadith extends Model
{
/**
* Get the book that owns the hadith.
*/
public function bookArray()
{
return $this->belongsTo(Books::class, 'book', 'bookSlug');
}
/**
* Get the chapter that owns the hadith.
*/
public function chapter()
{
return $this->belongsTo(Chapters::class, 'chapterId');
}
}
如果它们是分开的,这两种关系都很好,但正如我告诉你的那样,章节表有很多章节相同chapterNumber
但book slug
不同。
示例数据: 我有 2 本书:
- 布哈里圣训
- 穆斯林圣训
看我的桌子。
该chapter()
关系函数只会返回表中第一个章节,它只是检查chapterId
,它不会返回正确的值,因为hadiths
连接到两个books
和chapters
。
结果会是这样:
章节不属于,属于。
所以,我想做的是,首先得到拥有圣训的人,然后得到拥有书的章节。
有人可以帮我这样做吗?我被困住了
Revelation
hadith of Sahih Muslim book
hadith of Sahih Bukhari book
book
解决方案
推荐阅读
- powershell - PowerShell 中的递归 DFS
- google-cloud-sql - Google Cloud SQL 迁移作业卡在运行中
- arrays - 如何从 Java 中的 json 文件中读取 int 值?
- mongodb - db.collection.find() 返回省略 mongodb 中没有值的键
- javascript - 循环遍历对象数组以搜索来源 -> 目的地和目的地 -> 来源和拉取计数
- c++ - 从 resource.rc 创建文件返回 null
- angular - 如何处理对 asObservable() 公开的私有主题的多个订阅
- angular - CanActivate 使导航按钮被点击两次以改变屏幕
- vue.js - Router async beforeEach 触发两条路由
- wordpress - $wpdb->get_results 带变量