You say that you are getting all transactions, but the code only handles payment methods and bills?
Dec 3, 2022
6
Level 51
One to many relationship not working with whereHas condition
Hi
I have one-to-many relationship where one payment mode has many transaction. I want to filter transaction based on dates. So I tried with this query. But I 'm getting all the transaction. It's not getting filtered based on the dates. I don't know what is wrong in my code.
public function index()
{
$from_date = request()->from_date;
$to_date = request()->to_date;
$query = MstPayMode::with('bills');
$query->whereHas('bills', function ($q) use ($from_date, $to_date) {
$q->whereDate('bill_date', '>=', $from_date)
->whereDate('bill_date', '<=', $to_date);
});
$bills = $query
->get();
return view('admin.reports.bill-wise', compact('bills'));
}
Payment model
class MstPayMode extends Model
{
protected $table = 'mst_pay_mode';
protected $primaryKey = 'sk_payment_mode_id';
public function bills()
{
return $this->hasMany(Bill::class, 'mst_pay_mode_id', 'sk_payment_mode_id');
}
}
Transaction model
class Bill extends Model
{
protected $table = 'bill_bill_main';
protected $primaryKey = 'bill_id';
public $timestamps = false;
public function payment_mode()
{
return $this->belongsTo(MstPayMode::class);
}
}
Thank you
Level 102
Do you mean you want to limit with() as well?
$bills = MstPayMode::query()
->withWhereHas('bills', function ($q) use ($from_date, $to_date) {
$q->whereDate('bill_date', '>=', $from_date)
->whereDate('bill_date', '<=', $to_date);
})->get();
Please or to participate in this conversation.