- vừa được xem lúc

Sử dụng Laravel Eloquent withSum() and withCount()

0 0 60

Người đăng: Kumako

Theo Viblo Asia

Bài viết này mình sẽ giới thiệu các bạn cách sử dụng withSum() and withCount() với laravel relationship eloquent.
Để demo ví dụ mình sẽ tạo 2 tables là Category và Product và tạo relationship cho chúng.
Bạn có thể sử dụng withSum() & withCount() với laravel 6, laravel 7 & laravel 8 version.
Hãy xem ví dụ bên dưới nhé:

Category Model:

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; class Category extends Model
{ use HasFactory; /** * Get the products. */ public function products() { return $this->hasMany(Product::class); }
}

Product Model:

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model; class Product extends Model
{ use HasFactory; protected $fillable = [ 'name', 'price' ];
} 

Ví dụ withSum() :

<?php namespace App\Http\Controllers; use App\Models\Category; class SignaturePadController extends Controller
{ /** * Write code on Method * * @return response() */ public function index() { $categories = Category::select("id", "name") ->withSum('products', 'price') ->get() ->toArray(); dd($categories); }
} 

Output:

Array
( [0] => Array ( [id] => 1 [name] => Mobile [products_sum_price] => 330 ) [1] => Array ( [id] => 2 [name] => Laptop [products_sum_price] => 410 )
) 

sử dụng conditions trong withSum():

<?php namespace App\Http\Controllers; use App\Models\Category; class SignaturePadController extends Controller
{ /** * Write code on Method * * @return response() */ public function index() { $categories = Category::select("id", "name") ->withSum(['products' => function($query) { $query->where('publish', 1); }], 'price') ->get() ->toArray(); dd($categories); }
} 

Mình đã thêm điều kiện trong hàm withsum ở trên chỉ những thằng có publish =1 thì mới tính tổng

Ví dụ withCount():

<?php namespace App\Http\Controllers; use App\Models\Category; class SignaturePadController extends Controller
{ /** * Write code on Method * * @return response() */ public function index() { $categories = Category::select("id", "name") ->withCount('products') ->get() ->toArray(); dd($categories); }
} 

Output:

Array
( [0] => Array ( [id] => 1 [name] => Mobile [products_count] => 3 ) [1] => Array ( [id] => 2 [name] => Laptop [products_count] => 2 )
) 

Mình hy vọng bài viết này sẽ giúp ích cho các bạn!
Tham khảo: https://www.itsolutionstuff.com

Bình luận

Bài viết tương tự

- vừa được xem lúc

Laravel Best Practices - Code laravel thế nào cho chuẩn (P1)

1. Nguyên tắc ĐƠN TRÁCH NHIỆM - Single responsibility principle. Một lớp hay class chỉ nên có 1 trách nhiệm duy nhất. Đây là 1 trong các nguyên tắc của SOLID.

0 0 21

- vừa được xem lúc

Tips & best practices for Laravel 8

Hế lô các bạn ^^. Hôm nay mình sẽ chỉ cho bạn vài thủ thuật có thể nó sẽ giúp ích cho bạn khi viết code sử dụng Frameword Laravel nhé.

0 0 24

- vừa được xem lúc

WhereHas và With trong laravel

Hôm nay chúng ta cùng tìm hiểu WhereHas và With trong laravel nhé^^. Có thể bạn đã biết với Eloquent relationships mặc định thì access đến data trong Eloquent sẽ dùng"lazy loaded".

0 0 114

- vừa được xem lúc

20 tips xử lý dữ liệu với Eloquent trong laravel

1. Increments and Decrements. Article::find($article_id)->increment('read_count');. Article::find($article_id)->increment('read_count', 10); // +10.

0 0 19

- vừa được xem lúc

Hướng dẫn nén ảnh bằng TinyPNG Laravel PHP

Hi mọi người. Trước m lên diễn đàn Free Tuts gì đó hỏi nhưng ông chủ kênh thì nói cái này khó rồi này nọ, ghét cái thái độ (hơi nói xấu nhưng lỡ nói thì nói luôn).

0 0 22