laravel 搜索按子字段查询口才关系

qcbq4gxm  于 2022-12-24  发布在  其他
关注(0)|答案(2)|浏览(149)

我的产品型号是

public function IncomeRepo(){

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

我的收入报表模型是

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

我的查询是

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'));

 }

当我返回$ProductData时,它返回产品表created_at数据。但我需要收入表created_at数据,这是多个
我怎样才能得到它?
我的期望显示收入表created_at数据

wgx48brx

wgx48brx1#

如果你想通过子表日期过滤数据,那么你需要使用whereHas关系。

$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'));
r1wp621o

r1wp621o2#

在控制器中。(使用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'));
}

在视野中

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

相关问题