Ivan
Ivan

Reputation: 2481

Laravel: get children by parent slug

I have a Section and a Picture models, with a one-to-many relationship (Section can have many Pictures; Picture has only one Section)

I'm able to retrieve all Pictures given a Section id:

$section = '1';
$records = Picture::where('section_id', $section)->orderBy('position')->get();

What if I'd like to retrieve Picture by Section slug (or name)? All these examples don't work:

$section = 'wedding';
$records = Picture::where('sections.slug', $section)->orderBy('position')->get(); // nope
$records = Picture::where($this->section()->slug, $section)->orderBy('position')->get(); // nope

I tried to search in Laravel docs, but I didn't get the case... Thank you

Upvotes: 1

Views: 355

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17658

For querying relations you should use whereHas function.

If your relation is named section() in Picture model then your query should be as:

$section = 'wedding';

$records = Picture::whereHas('section', function($q) use($section) {
                            $q->where('slug', $section);
                        })
                        ->orderBy('position')
                        ->get();

Docs

Upvotes: 2

Related Questions