Home > Back-end >  Search Query by Child field Eloquent relation
Search Query by Child field Eloquent relation

Time:12-20

My Product Model is

public function IncomeRepo(){

        return $this->hasMany(Income::class,'Product');
    }

My Income Report Model Is

 public function ProductData(){
        
        return $this->belongsTo(Product::class,'Product','id');
    }

My Query is

public function SearchIncomeData(Request $request){

    $GetFromDate = $request->FromDate;
    $GetToDate = $request->ToDate;
        
        $ProductData = Product::with('IncomeRepo')->whereBetween('created_at', [$GetFromDate, $GetToDate])->get();
        
       return view('Admin.Report.ProductSalesReport',compact('ProductData'));

 }

When I return $ProductData it return products table created_at Data. BUT I nee Income table created_at data which be multiple

How can I get it?

My expectation show incomes table created_at data

CodePudding user response:

If you want to filter data by child tables date then you need to use whereHas relationship.

$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
    
$ProductData = Product::with('IncomeRepo')
           ->whereHas('IncomeRepo',function($que) use($GetFromDate,$GetToDate) { 
           $que->whereBetween('created_at',[$GetFromDate, $GetToDate])})->get();
    
return view('Admin.Report.ProductSalesReport',compact('ProductData'));

CodePudding user response:

In controller. (Use whereBetween)

public function SearchIncomeData(Request $request)
{
    $GetFromDate = $request->FromDate;
    $GetToDate = $request->ToDate;

    $ProductData = Product::with(['IncomeRepo' => function ($query) use ($GetFromDate, $GetToDate)
    {
        $query->whereBetween('created_at', [$GetFromDate, $GetToDate]);
    }
    ])->get();

    return view('Admin.Report.ProductSalesReport', compact('ProductData'));
}

In view

foreach ($ProductData as $product)
{
    foreach ($product->IncomeRepo as $income)
    {
        echo $income->created_at;
    }
}
  • Related