繁体   English   中英

使用Laravel Eloquent查询Where子句

[英]Where clause query using Laravel Eloquent

我让这段代码正常工作$sector = Sector::where('ref_id', $sectorId)->with('offers.provider')->first(); 为了更好的灵活性和对我想做什么的理解,已将其更改为以下代码:

$sector = Sector::where('ref_id', '$sectorId')
->with(
    [
        'offers' => function($query) {
            $query->with(
                [
                    'provider' => function($query) {
                        $query->select('name');
                    }
                ]
            );
        }
    ]
)
->first();

因此,在这里我们采用一个sector ,该offers链接到该sector ,在每个offer之下,我们采用链接的provider 现在, providersstatus01 因此,基于以上我的代码,有没有办法只能检索到offers ,它们是具有providers与状态1

请帮助我解决这个问题。

您是否尝试过在提供者查询中添加where子句以仅获取状态为1的提供者?

'provider' => function($query) {
    $query->select('name')->where('status', 1);
}

编辑:我不是Laravel的专家,但也许我遇到问题的一个查询示例可能会阐明您的问题:

$dealer = $this->dealer->where('foreign_dealer_id', $dealerIdInFeed)
            ->where(function ($subQuery) use ($accountTypes) {
                if(count($accountTypes) > 1)
                {
                    foreach($accountTypes as $accountType)
                    {
                        $subQuery->orWhere('account_type', $accountType);
                    }
                }
                else
                {
                    $subQuery->orWhere('account_type', $accountTypes);
                }
            })
            ->first();

您可以使用whereHas-这是专门为此类情况设计的。 来自文档的示例:

如果您需要更多功能,则可以使用whereHas和orWhereHas方法在您的条件查询中放置“ where”条件。 这些方法使您可以向关系约束中添加自定义约束,例如检查注释的内容:

// Retrieve all posts with at least one comment containing words like foo%
$posts = Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', 'foo%');
})->get();

不要让代码片段欺骗您,它会像上面一样在closure内完美运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM