Bryant Tang
Bryant Tang

Reputation: 251

Laravel belongsTo where condition

I wanna filter today date, but it seems does not work. This function is a relation in class.

$manpower = Manpower::with(['pwra.purchaseOrder'])->get();

// Manpower Class

public function pwra()
{
    return $this->belongsTo('App\Models\Pwra', 'pwra_uuid', 'pwra_uuid')->where('pwra_dt', Carbon::today());
}

// Pwra Class

public function purchaseOrder()
{
    return $this->hasMany('App\Models\PurchaseOrder', 'purchase_order_uuid', 'purchase_order_uuid');
}

Without where case:

enter image description here

enter image description here

Upvotes: 0

Views: 1686

Answers (3)

Bryant Tang
Bryant Tang

Reputation: 251

$manpower = Manpower::whereHas('pwra.purchaseOrder', function (Builder $query) {
    $query->where('pwra_dt', date('Y-m-d'));
})->get();

Upvotes: 0

gbalduzzi
gbalduzzi

Reputation: 10166

My guess is that pwra_dt is a timestamp, not just a date in the DB. Try this:

public function pwra()
{
    return $this->belongsTo('App\Models\Pwra', 'pwra_uuid', 'pwra_uuid')
      ->where('pwra_dt', '>=', Carbon::today())
      ->where('pwra_dt', '<', Carbon::tomorrow());
}

Upvotes: 0

hammad khan
hammad khan

Reputation: 65

you should write query like this.

Model::with(['relationMethod'=>function($query){
            return $query->where('pwra_dt', date('Y-m-d'))->get();

        }]) ->get();

Upvotes: 1

Related Questions