Laravel 与多表的雄辩关系

时间:2021-07-23 17:57:18

标签: php laravel eloquent laravel-8

我有 3 个表,我正在建立这些表的关系,但是我无法实现。我有 3 个名为 BooksChaptersHadith 的表。 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 是不同的。

示例数据: 我有两本书:

<块引用>
  1. 布哈里圣训
  2. 穆斯林圣训

现在,我有很多这样的书的章节。 enter image description here
enter image description here

现在,在圣训中: enter image description here enter image description here

查看我的表格。
那个chapter()关系函数只会返回表中第一个的章节,它只检查chapterId,它不会返回正确的值,因为hadiths连接到两个bookschapters
结果会是这样:
enter image description here
章节Revelation不属于hadith of Sahih Muslim book,它属于hadith of Sahih Bukhari book
所以,我想要做的是,先获取拥有圣训的book,然后获取拥有书的章节。
有人可以帮我做到这一点吗?我卡住了

0 个答案:

没有答案