我試圖測驗記錄何時為空。不知道為什么這不起作用。user_id 是我的 FK。當沒有記錄時,我喜歡它顯示它是空的,當它被添加時顯示它被添加。我手動添加洗掉記錄來測驗它。
移民
Schema::create('business_dashboards', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('business_name');
$table->string('website');
$table->timestamps();
});
模型
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class BusinessDashboard extends Model
{
use HasFactory;
protected $fillable = [
'business_name',
'website',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function userprofile()
{
return $this->belongsTo(User::class);
}
}
控制器
$businessDashboardUserId = BusinessDashboard::where('user_id', null)->first();
if ($businessDashboardUserId) {
dd('Is Null');
} else {
dd('Not Null');
}
資料庫表

uj5u.com熱心網友回復:
有條件地嘗試whereNull()和count()
$businessDashboardUserId = BusinessDashboard::whereNull('user_id')->first();
if (!$businessDashboardUserId->count()) {
dd('Is Null');
} else {
dd('Not Null');
}
或者更好
if (!BusinessDashboard::whereNull('user_id')->exists()) {
dd('Is Null');
} else {
dd('Not Null');
}
uj5u.com熱心網友回復:
通常,人們會為此使用 Eloquent 關系。您當前的方法存在問題,例如回傳BusinessDashboard可能被軟洗掉的User實體,或者不忽略可能被軟洗掉的實體。
$businessDashboard = BusinessDashboard::whereDoesntHave('userprofile')->first();
提供更多代碼可能有助于用戶了解您要實作的目標,并能夠提供更完整的建議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/372556.html
