วันอาทิตย์ที่ 8 พฤษภาคม พ.ศ. 2559

การนำจำนวนกับตารางที่มีความสัมพันธ์แบบ hasMany (laravel)

 การนำไปใช้งานคือ  copy and paste     555

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
// Post model
public function commentsCount()
{
  return $this->hasOne('Comment')
    ->selectRaw('post_id, count(*) as aggregate')
    ->groupBy('post_id');
}
 
public function getCommentsCountAttribute()
{
  // if relation is not loaded already, let's do it first
  if ( ! array_key_exists('commentsCount', $this->relations))
    $this->load('commentsCount');
 
  $related = $this->getRelation('commentsCount');
 
  // then return the count directly
  return ($related) ? (int) $related->aggregate : 0;
}


commentsCount()

getCommentsCountAttribute()

การนำไปใช้งานให้ระวัง   ต้องชื่อฟังก์ชั่นให้สีเหลืองเหมือนกันตัวเล็กตัวใหญ่มีค่าเท่ากัน



ที่มา
https://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/

ไม่มีความคิดเห็น:

แสดงความคิดเห็น