【问题标题】:Laravel 8: Check if Record in Database is EmptyLaravel 8:检查数据库中的记录是否为空
【发布时间】:2022-01-09 10:10:35
【问题描述】:

我正在尝试测试记录何时为空。不知道为什么这不起作用。 user_id 是我的外键。当没有记录时,我喜欢它显示它是空的,并且当它被添加以显示它被添加时。我正在手动添加删除记录来测试它。

迁移

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');
    }

数据库表

【问题讨论】:

  • 不工作到底如何?这段代码的结果是什么?还有一件事当user_id 为空时,您正试图获得BusinessDashboard,这很确定它不会返回任何内容。
  • 检查表中是否存在某些内容的更好方法是使用existsmethod。示例:if (BusinessDashboard::where('user_id', null)->exists()) { // yes } else { // no }。但话又说回来,您也可以使用whereNull 而不是where。 @Ginz77
  • 你实际期待什么结果,因为这看起来很奇怪

标签: php laravel database laravel-8


【解决方案1】:

尝试使用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');
}

【讨论】:

  • 仍然没有给我结果。模型或迁移可能有问题吗?我在帖子中添加了其他代码。
猜你喜欢
  • 2016-07-15
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 2013-08-07
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
相关资源
最近更新 更多