簡體   English   中英

Laravel 布爾值返回錯誤數據

[英]Laravel boolean value return wrong data

我在這個表中有表名payments ,每一行都有名為paid的列,它是布爾值。 當我嘗試根據此paid列獲取單獨的付費和未付費行列表時,它只會返回所有行。

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 employee_id = 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM