[英]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.