我有 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
是不同的。
示例数据: 我有两本书:
<块引用>查看我的表格。
那个chapter()
关系函数只会返回表中第一个的章节,它只检查chapterId
,它不会返回正确的值,因为hadiths
连接到两个books
和chapters
。
结果会是这样:
章节Revelation
不属于hadith of Sahih Muslim book
,它属于hadith of Sahih Bukhari book
。
所以,我想要做的是,先获取拥有圣训的book
,然后获取拥有书的章节。
有人可以帮我做到这一点吗?我卡住了