JohnMi
JohnMi

Reputation: 81

Laravel relation returning empty

I want to get all the books under a certain category. The category has many subjects and books are linked to subjects.

My code:

class BookCategory extends Model {

    public function subjects() {
        return $this->hasMany('BookSubject', 'category_id', 'id');
    }

    public function getBooksAttribute() {
        return Books::whereHas('subjects', function ($query) {
            return $query->join('book_category', 'book_category.id', '=', 'book_subject.subject_id')
                         ->where('book_category.id', $this->id);
        })->get();
    }
}

and my Books model:

class Books extends Model {

    public function subjects() {
        return $this->belongsToMany('BookSubject', 'book_by_subject', 'book_id', 'subject_id');
    }
}

If I do:

$cats = \App\Models\BookCategory::all();
foreach ($cats as $c) {
    echo $c->books->count();
}

It's always returning 0 for all the rows. What I'm I doing wrong?

Upvotes: 0

Views: 117

Answers (1)

Pitchinnate
Pitchinnate

Reputation: 7556

I believe the problem is in your subquery:

return $query->join('book_category', 'book_category.id', '=', 'book_subject.subject_id')
                     ->where('book_category.id', $this->id);

I'm pretty sure book_subject.subject_id should be book_subject.category_id

Hard to tell without seeing your db schema.

Upvotes: 1

Related Questions