簡體   English   中英

你如何為 Laravel 中是否存在記錄設置布爾值?

[英]How do you set a boolean for whether a record exists in Laravel?

我正在嘗試根據表中是否存在記錄來設置布爾值$bln

這是我一直在嘗試的:

$bln = (bool) DB::table('accounts')->where('name', $name)->pluck('id');

出於某種原因, $bln似乎總是被設置為true 我究竟做錯了什么?

為此,您可以使用count()方法:

$bln = DB::table('accounts')->where('name', $name)->count() > 0;

如果稍后需要該對象,請加載它並使用is_null()進行檢查:

$object = DB::table('accounts')->where('name', $name)->first();
$bln = !is_null($object);

我猜idinteger而不是boolean類型? 好吧,我真的希望它是! 呵呵。
您所做的是獲取給定accountid並將其轉換為bool
如果你將一個值轉換為bool ,只要它不計算為false ,它就會為,在integers情況下,當你將它轉換為bool時,只有0會被計算為false

檢查結果計數是否大於0 ,它應該給出你想要的結果。

因為 pluck() 返回一個數組,你可以用 count $bln = (bool) count(DB::table('accounts')->where('name', $name)->pluck('id')); 這是Laravel 文檔:pluck()

請試試這個。

$bln = DB::table('accounts')->where('name', $name)->get()->first();
if(isset($bln) && $bln != null || $bln != ''){
    return $bln = 1;
}
else{
    return $bln = 0;
}

exists()doesntExist()方法直接給出一個布爾值,使用它們代替count()

$bln = DB::table('accounts')->where('name', $name)->exists();

Laravel 文檔:確定記錄是否存在

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM