如何在laravel中添加对关系数据的查询

时间:2019-03-06 07:47:02

标签: laravel

我的查询是

$payment_history=User::where('name','like','%'.$search.'%')
->orWhere('email','like','%'.$search.'%')
->with(['payment_history'=>function($query,$request){
                $query->whereBetween('date', array($request->from, $request->to))
                      ->orderBy('id','Desc');
}])
->paginate(30);

我得到这个错误:

Missing argument 2 for App\Http\Controllers\Payment\PaymentController::App\Http\Controllers\Payment\{closure}(), called in /var/www/html/panel/vendor/laravel/fr ▶

谢谢

2 个答案:

答案 0 :(得分:0)

您不能将$request用作类似function($query,$request)的函数参数。您需要使用它function($query) use ($request)

$payment_history = User::where('name', 'like', '%'.$search.'%')
    ->orWhere('email', 'like', '%'.$search.'%')
    ->with(['payment_history' => function($query) use ($request){
        $query->whereBetween('date', array($request->from, $request->to))
              ->orderBy('id', 'Desc');
    }])->paginate(30);

答案 1 :(得分:0)

据我了解,您的关闭错误是由第二个参数器引起的-您将$request用作第二个参数器是错误的。

代替

function($query,$request) 

应该是

function($query) use($request)

不是你做的方式。

$payment_history=User::where('name','like','%'.$search.'%')
->orWhere('email','like','%'.$search.'%')
->with(
     ['payment_history'=>function($query) use($request){
         $query->whereBetween('date', array($request->from, $request->to))
         ->orderBy('id','Desc');
  }]
)
->paginate(30);