首页 文章

使用Eloquent选择关系计数为零的所有记录?

提问于
浏览
2

用简单的英语:我有三张 table . subscription_type 有很多 email_subscription ,其中有很多 email .

我正在尝试选择具有特定 subscription_type 的所有 email_subscription 记录,这些记录也没有任何关联的_10957__记录 statusHeld .

我坚持的特定位只返回 email_subscriptions ,它具有零 emails (在上面描述了一个额外的where子句) .

使用Eloquent,我已经能够得到一些方法,但我不知道如何选择关系计数为零的所有记录:

$subscriptionsWithNoCorrespondingHeldEmail = EmailSubscriptions::whereHas('subscriptionType', function($q) {
            $q->where('name', 'New Mission');
        })-; // What do I chain here to complete my query?

另外,Eloquent甚至可以实现这一点,还是需要使用Fluent语法?

2 回答

  • 5

    您可以使用 has() 方法查询关系存在:

    has('emails', '=', 0)
    

    例如:

    $tooLong = EmailSubscriptions::whereHas('subscriptionType', function($q) {
        $q->where('name', 'New Mission');
    })->has('emails', '=', 0)->get();
    

    Edit

    您可以使用 whereHas()whereDoesntHave() 方法执行更多高级查询:

    $tooLong = EmailSubscriptions::whereHas('subscriptionType', function($q) {
        $q->where('name', 'New Mission');
    })
    ->whereDoesntHave('emails', function ($query) {
        $query->where('status', '=', 'whatever');
    })->get();
    
  • 0

    好吧,我对你的问题的看法是你希望有一个所有的电子邮件

    特定subscription_type,零(0)关联和状态=状态

    如果是,那么你可以在where语句中使用数组 . 喜欢:

    $q->->where(array('status' => 'status','subscription_type'=>'what ever you want));
    

相关问题