2015-10-04 38 views
1

關係我有2個表如下:Laravel 4:計算內whereHas

Subscription表具有entrance_limit柱,它有一個hasMany('Attendance')關係。 entrance_limit列實際上會限制Attendance中的行數。例如,如果entrance_limit的值爲10,那麼我們只能在Attendance中創建10行。

Attendance表具有belongsTo('Subscription')的關係。

我如何獲得總數爲Attendance小於entrance_limit值的Subscription列表?

Subscription::whereHas('attendances', function($q) { 
    ## something like this 
    $q->count() < subscription->entrance_limit 
}) 

回答

0

最後能得到它一起工作的下列內容:

Subscription::whereRaw(' 
    (select count(*) from `attendances` where `attendances`.`subscription_id` = `subscriptions`.`id`) < `subscriptions`.`entrance_limit` 
'); 
0

型號查詢低於

Subscription::whereHas('attendances', function($q) { 
    $q->where('entrance_limit','>',$q->count()); 
})