Laravel 布尔值 return 错误数据

Laravel boolean value return wrong data

我在这个 table 中有 table 名称 payments 每行都有名为 paid 的列,它是布尔值。当我尝试根据此 paid 列获取单独的付费和未付费行列表时,它只是 return 所有行。

Code

获取未付费行

$purchases = Payment::wherePaid(false)
    ->where('employee_id', $user->id)
    ->orWhere('employer_id', $user->id)->with([
        'employer',
        'employee' => function($q) {
            $q->select(['id', 'first_name', 'last_name']);
        },
        'template',
        'training',
        'contract',
    ])->get();

获得付费行数

$purchases = Payment::wherePaid(true)
    ->where('employee_id', $user->id)
    ->orWhere('employer_id', $user->id)->with([
        'employer',
        'employee' => function($q) {
            $q->select(['id', 'first_name', 'last_name']);
        },
        'template',
        'training',
        'contract',
    ])->get();

Model

protected $casts = [
  'paid' => 'boolean',
];

在这两个查询中,我得到了 4 个数组,其中包括 3 个未付费行和 1 个付费行。

更新

Schema

public function up()
{
    Schema::create('payments', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('employer_id')->nullable();
        $table->unsignedBigInteger('employee_id')->nullable();
        $table->unsignedBigInteger('template_id')->nullable();
        $table->unsignedBigInteger('contract_id')->nullable();
        $table->unsignedBigInteger('training_id')->nullable();
        $table->string('duration')->nullable();
        $table->string('amount');
        $table->boolean('paid')->default(false);
        $table->string('booking_id')->nullable();
        $table->string('invoice_no');
        $table->timestamps();
    });
    Schema::table('payments', function (Blueprint $table) {
        $table->foreign('employer_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('employee_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('template_id')->references('id')->on('contract_templates')->onDelete('cascade');
        $table->foreign('contract_id')->references('id')->on('contracts')->onDelete('cascade');
        $table->foreign('training_id')->references('id')->on('trainings')->onDelete('cascade');
    });
}

我可能错了,但我认为你的问题是你要求 paid = false AND employee_id = ID OR employer_id = ID。我觉得MySQL在想:

(paid = false AND employee_id = ID) OR (employer_id = ID)

所以,试试这个查询:

$purchases = Payment::wherePaid((false or true))
    ->where(function ($query) use ($user) {
        return $query->where('employee_id', $user->id)
            ->orWhere('employer_id', $user->id)
    })
    ->with([
        'employer',
        'employee' => function($query) {
            return $query->select(['id', 'first_name', 'last_name']);
        },
        'template',
        'training',
        'contract',
    ])
    ->get();

这会将查询更改为:

(paid = false or true) AND (employee_id = ID OR employer_id = ID)