2017-04-17 99 views
-1

我的代码中有一个很大的问题。我试图返回0,如果想要的行,返回null(这意味着没有数据符合搜索条件)如何在Laravel中返回0而不是null

我的查询是:

$total7 = DB::table('agencies') 
->join('users' , 'users.id' , '=' , 'agencies.user_id') 
->join('user_addresses' , 'user_addresses.user_id' , '=' , 'users.id') 
->join('cities' , 'cities.id' , '=' , 'user_addresses.city_id') 
->join('country_states', 'country_states.id' , '=' , 'cities.state_id') 
->select('agencies.id as agenID ','country_states.name as sName', DB::raw('count(agencies.id) as agencount') , 'agencies.created_at as agencreate') 
->where ('country_states.name','=','Capital Governorate') 
->whereNULL ('agencies.id') 
->whereBetween('agencies.created_at' , ['2017-01-01' , '2017-03-31']) 
->groupBy(DB::raw("MONTH(agencies.created_at)") , 'country_states.name') 
->get(); 

这种说法应该返回0,0,2但现在它什么也不返回 我希望它搜索抛出指定的月份范围(3个月),并返回值如果存在或0如果没有值。 我试过IFNULL但没有。 有什么帮助吗?

+0

- > whereNULL('agencies.id') 我真的不理解这部分。如果ID是一个自动增量值,为什么你检查它是否为空?它永远不会是null –

+0

@Rodrane我试图让任何参数,使我的声明工作,因为我想。如果本月没有该省的身份证,则返回零。 – imohd23

+0

当你完成你的查询后,只需做简单的(!$ result)? –

回答

0

尝试检查计数集合:

使用IFNULL:$total7->count(); `

+0

它只显示我返回的值的数量不是我所需要的,这是抛出第一个月,如果有价值,打印它,如果不给我零。 – imohd23

0

您可以从查询做

IFNULL(字段名,0)

+0

我没有得到如何使用IFNULL,因为它之前测试它,没有任何值得发生 – imohd23

0
if(!$total7) { 
     $result = 0; 
    } 

然后在您的控制器或您的刀片文件中使用$result变量您想要的,

0

更新答案:

我改变了查询的条款返回我只需要哪个是

count(agencies.id) 

所以查询与输出的代码是:

$countt = 3; 
$ii = 1; 
do{ 

        $total7 = DB::table('agencies') 
->join('users' , 'users.id' , '=' , 'agencies.user_id') 
->join('user_addresses' , 'user_addresses.user_id' , '=' , 'users.id') 
->join('cities' , 'cities.id' , '=' , 'user_addresses.city_id') 
->join('country_states', 'country_states.id' , '=' , 'cities.state_id') 
->select(DB::raw('ifnull(count(agencies.id),0) as agencount')) 
->where ('country_states.name','=', $gover) 
->whereMonth('agencies.created_at' , $ii) 
->groupBy(DB::raw("MONTH(agencies.created_at)") , 'country_states.name') 
->first(); 
if (count($total7) == 0){ 
    echo '0,'; 
}else{ 
    echo $total7->agencount.','; 
} 


$ii++; 

}while ($ii <= $countt); 

$gover是来自另一个更大的foreach循环来扔掉所有的省我有一个值。 $ii是一个计数器作为月份计数器来搜索投掷月份的想要的范围。做查询搜索直到你达到想要的月份的限制(从1到3是3个月)。 如果当前月份没有值,则返回值将为0,如果其值为0,则打印它,否则返回值。

我感谢所有对这个问题发表评论的人。我对你有利。