首页 > 解决方案 > Laravel 与多个表的雄辩关系

问题描述

我有 3 个表,我正在建立这些表的关系,但是我无法实现它。我有 3 个名为Books, Chapters&的表HadithBooks有很多章节的数据,有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');
    }
}

如果它们是分开的,这两种关系都很好,但正如我告诉你的那样,章节表有很多章节相同chapterNumberbook slug不同。

示例数据: 我有 2 本书:

  1. 布哈里圣训
  2. 穆斯林圣训

现在,我有很多这样的书的章节。 在此处输入图像描述
在此处输入图像描述

现在,在圣训中: 在此处输入图像描述 在此处输入图像描述

看我的桌子。
chapter()关系函数只会返回表中第一个章节,它只是检查chapterId,它不会返回正确的值,因为hadiths连接到两个bookschapters
结果会是这样: 章节不属于,属于。 所以,我想做的是,首先得到拥有圣训的人,然后得到拥有书的章节。 有人可以帮我这样做吗?我被困住了
在此处输入图像描述
Revelationhadith of Sahih Muslim bookhadith of Sahih Bukhari book
book

标签: phplaraveleloquentlaravel-8

解决方案


推荐阅读