[英]The number of records in the relation in Laravel
]我是初學者php開發人員。 我在 Laravel 5.6 中有項目。
我有 2 次遷移:
class CreateStopwatches extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stopwatches', function (Blueprint $table) {
$table->increments('id');
$table->integer('case_id')->unsigned();
$table->foreign('case_id')->references('id')->on('case_instances')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('stopwatches');
}
}
class CreateStopwatchTimeCycles extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('stopwatch_time_cycles', function (Blueprint $table) {
$table->increments('id');
$table->morphs('timecycle');
$table->boolean('status')->default(0);
$table->integer('worked_time')->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('stopwatch_time_cycles');
}
}
和型號:
class Stopwatch extends Model
{
protected $fillable = [
'case_id'
];
protected $casts = [
'id' => 'int',
'case_id' => 'int',
];
protected $dates = [
'created_at',
'updated_at'
];
public function timeCycle()
{
return $this->morphMany(StopWatchTimeCycle::class, 'timecycle');
}
}
class StopwatchTimeCycle extends Model
{
protected $fillable = [
'case_id'
];
protected $casts = [
'id' => 'int',
'case_id' => 'int',
];
protected $dates = [
'created_at',
'updated_at'
];
public function stopwatch()
{
return $this->morphTo();
}
}
在我的控制器中,我需要返回 1 - 當秒表有 stopwatches_time_cycles 時。 我制作了這個控制器:
public function checkActivity(int $caseId)
{
if (Stopwatch::with(['timeCycle'])->where('case_id', $caseId)->withCount('timeCycle')->first() === 0) {
return 0;
} else {
return 1;
}
}
但它不能正常工作。 它總是返回 1(我有空表 stopwatch_time_cycles)。
我該如何修復它?
請幫我
在第一個 if 語句中,您將整個 StopWatch 對象與零進行比較。 這就是導致錯誤的原因。
您應該將秒表保存在一個變量中:
$stopwatch = Stopwatch::with(['timeCycle'])->where('case_id', $caseId)->withCount('timeCycle')->first();
然后,要進行檢查,如果 timeCycles 存在,您可以執行以下操作:
if($stopwatch->timeCycle->count() == 0){
...
} else {...}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.