DEV Community

Zain Shabir
Zain Shabir

Posted on

Laravel multiple tables relationship not working

I have 3 tables named books, chapters & hadiths (blogs). I am getting hadiths but i want the hadiths data with chapter and book. bookSlug is the column name which connected the 3 tables, and chapterId is the column which connected the hadith and chapter.
belongsTo, hasOneThrough or any other relation is not working for me. So, i created a custom relationship in Hadith model like this:
public function chapter($chapterNumber, $bookSlug)
{
return Chapters::where([
['chapterNumber', $chapterNumber],
['bookSlug', $bookSlug]
])->first();
}

But i can't use this relation in Hadith query with function with(), because my custom relationship has function parameters.
Maybe I am missing something, but is there any way i can achive it using laravel built-in relations?

My tables structure:
books:
id,
bookName
bookSlug

chapters:
id,
chapterNumber,
chapterName,
bookSlug

hadiths:
id,
hadithEnglish,
chapterId,
bookSlug

I just want to do in Hadith model like this that:
Get a hadith where in the chapter table the chapterNumber column is equals to the column chapterId of hadith table, and then where in the hadith table the bookSlug column is equals to the column bookSlug of chapter table.
Is this possible? I am stuck

Top comments (0)