在包含关系的模型中,使用withSum方法来对关联模型中的字段进行求和。该方法接受两个参数,第一个参数是关联模型的名称,第二个参数是要求和的字段名称。 例如,假设我们有一个User模型和一个Order模型,它们之间是一对多的关系,一个用户可以有多个订单。我们想要对用户的订单总金额进行求和,可以使用以下代码: 例如...
韩众39 声望 PHP @ 未名
23 Orm::withCount(['relation as relation_sum'=>function($query){ $query->select(DB::raw("sum(amount) as relationsum")); }])
Orm::withCount(['relation as relation_sum'=>function($query){ $query->select(DB::raw("sum(amount) as relationsum")); }]) 1. 2. 3.
Model::with('relation')->get(); Model::all()->take(10); Model::all()->skip(10); // 默认的 Eloquent 排序是上升排序 Model::all()->orderBy('column'); Model::all()->orderBy('column','desc'); 软删除 Model::withTrashed()->where('cars', 2)->get(); // 在查询结果中包括带...
*/publicfunctionuser(){return$this->belongsTo(User::class)->withDefault();} 如果想要这个默认模型中包含一些属性的话,那么您可以向withDefault方法中传递一个数组或者一个闭包: /** * 获取这篇博客所属的用户。 */publicfunctionuser(){return$this->belongsTo(User::class)->withDefault(['name'=>'Gue...
In addition to the withCount method, Eloquent provides withMin, withMax, withAvg, withSum, and withExists methods. These methods will place a {relation}_{function}_{column} attribute on your resulting models:use App\Models\Post; $posts = Post::withSum('comments', 'votes')->get(); for...
:with(['relation'=>function($query){}])->get();//只查找符合条件的关联数据 Model::whereHas('relation',function($query){ ... })->get();//1对多关联,查找关联数据符合条件的数据 Model::whereNotExists(function($query){ $query->from(...
除了withCount 方法外,Eloquent 还提供了 withMin, withMax, withAvg 和withSum 等聚合方法。这些方法会通过 {relation}_{function}_{column} 的命名方式将聚合结果添加到获取到的模型属性中:use App\Models\Post;$posts = Post::withSum('comments', 'votes')->get();foreach ($posts as $post) { echo...
Model::with('relation')->get();Model::all()->take(10);Model::all()->skip(10);// 默认 Eloquent 排序方兴未艾Model::all()->orderBy('column');Model::all()->orderBy('column','desc'); Soft Delete 123456 Model::withTrashed()->where('cars', 2)->get();// 在结果中包含软删除模型...