Laravel 5.1 Eloquent或Where子查询

时间:2016-03-18 06:10:27

标签: mysql laravel eloquent

我对这个问题感到失望。我真的需要这方面的帮助:

SELECT COUNT(*) FROM customers
WHERE (SELECT count(*) FROM customerEmails WHERE email = :email) > 0 
OR (SELECT count(*) FROM customerPhoneNumbers WHERE phoneNumber = :cellphone) > 0 
OR cellphone = :cellphone 
OR email = :email

我不知道对于这个应该是雄辩的代码。 TIA!

1 个答案:

答案 0 :(得分:2)

您可以使用Eloquent的whereHas(稍微高于该锚点)方法来有条件地加载Customer,具体取决于它们与其他实体的关系。假设您有一个名为Customer的模型,您可以尝试:

$count = Customer::whereHas('customerEmails', function ($query) use ($email){
    $query->where('email', $email);
})
->orWhereHas('customerPhoneNumbers', function ($query) use ($cellphone){
    $query->where('phoneNumber', $cellphone);
})
->orWhere('cellphone', $cellphone)
->orWhere('email', $email)
->count();