【问题标题】:Laravel: get children by parent slugLaravel:通过父母蛞蝓获取孩子
【发布时间】:2016-11-27 18:35:57
【问题描述】:

我有一个部分和一个图片模型,具有一对多的关系(部分可以有很多图片;图片只有一个部分)

我能够检索给定部分 id 的所有图片:

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

如果我想按部分 slug(或名称)检索图片怎么办? 所有这些例子都不起作用:

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

我尝试在 Laravel 文档中进行搜索,但没有找到案例... 谢谢

【问题讨论】:

    标签: laravel-5


    【解决方案1】:

    对于查询关系,您应该使用whereHas 函数。

    如果您的关系在Picture 模型中被命名为section(),那么您的查询应该是:

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

    Docs

    【讨论】:

    • 哦,我认为它更“立即”...不过谢谢,这行得通!
    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2017-10-25
    相关资源
    最近更新 更多