You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel关联查询需求:排除含renewal=1的关联数据

Fixing the Officiant Query to Exclude Any with Renewed Credentials

Hey there! I see what you're trying to do here—your current query pulls in Officiants who have at least one cred record with renewal = 0, but it doesn't account for cases where an Officiant might have another cred record with renewal = 1. That means you could still end up with Officiants you want to exclude.

Here's the corrected approach: we need to filter out any Officiant that has even one cred record where renewal = 1, while keeping only those who have all their cred records marked with renewal = 0 (plus matching your original status = 1 filter).

The Updated Code

$officiants = Officiant::where('status', 1)
    // Exclude any Officiant with a cred record where renewal is 1
    ->whereDoesntHave('cred', function($q) {
        $q->where('renewal', 1);
    })
    // Optional: Ensure the Officiant has at least one cred record (matches your original logic)
    ->whereHas('cred')
    ->get();

How This Works:

  • whereDoesntHave('cred', ...): This is the critical piece. It eliminates any Officiant that has any associated cred record marked as renewed (renewal = 1). Exactly what you need—if even one cred is renewed, they get excluded entirely.
  • The optional whereHas('cred'): This keeps alignment with your original query, ensuring we only return Officiants who have at least one cred record. If your business allows Officiants without any cred records to be included, you can safely remove this line.

Quick Note:

If your cred relationship is one-to-one instead of one-to-many, this logic still works perfectly—whereDoesntHave will simply check that the single associated cred isn't marked as renewed.

内容的提问来源于stack exchange,提问作者Victor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:02:12