比较 laravel 中的两个表以检查表中是否存在一行

Comparing two tables in laravel to check if a row exists in the tables

非常快,我正在处理这个学校项目,但在我看来有些问题。

我有:

Table A - 费用:

id | feename | fee_level | fee_acad_year

Table B - 付费费用:

id | fee_id | student_number | payment_status

所以我想做的是,我想遍历所有费用的费用 table,然后转到付费费用 table 以检查是否 fee_id 存在关于学生的编号,付款状态仅为 1,即已付款。

如果 fee_id 存在,它应该将它们标记为付费的,并将它们作为付费的存储在数组中。

然后,如果它不存在,它应该将它们存储在另一个数组中作为未付费的。

这是我的代码:

// Fetch All fees for that level, semester and acamedic year 
        $fees = DB::table('fee')
            ->where([
                ['fee.Department','=',$csl->departmentid],
                ['fee.Semester','=',$csl->semesterid],
                ['fee.StudentLevel','=',$csl->levelid]
            ])
            ->select('id')
            ->get();
    }

    //return $fees;

    $feeids = array();
    foreach($fees as $fee){
        $feeids[] = $fee->id;
    }
    //dd($feeids);

    // Select all from paid fees
    $paidFees = PaidFees::all();

    $paidFeeIds = array();
    foreach($paidFees as $pd) {
        $paidFeeIds[] = $pd->FeeId;
    }
    $status = "";
    if(in_array($feeids, $paidFeeIds)) {

        $status = "paod";
    }else {
        $status = "Not Paid";
    }

这是我感到困惑的部分。

如果您需要一组已付费用ID和一组未付费用ID,您可以使用Eloquent。

首先,定义一个关系:

public function paidFees()
{
    return $this->hasMany(PaidFees::class, 'fee_id');
}

然后获取ID:

$paidFeesIds = Fee::whereHas('paidFees', function($q) {
    $q->where('payment_status', 1);
})->pluck('id')->toArray();

$notPaidFeesIds = Fee::whereNotIn('id', $paidFeesIds)->pluck('id')->toArray();