2016-07-07 23 views
4

我需要計算後多少評論了。我會怎麼做呢?計數後有多少評論有 - Laravel 5.2

這裏是我的Listing.php型號:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Listing extends Model 
{ 

    public function reviews() 
    { 
     return $this->hasMany('\App\Review'); 
    } 

} 

這裏是我的Review.php型號:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Review extends Model 
{ 
    protected $fillable = ['stars','name','comment']; 

    public function listing() 
    { 
     return $this->belongsTo('\App\Listing'); 
    } 
} 

這裏是我的方法是我'試圖在控制器來算

public function mostReviews(Request $request) { 

     $listings = Review::orderBy('-- most reviews here --')->take(10)->get(); 

     $headline = 'Most Reviewed Listings'; 

     return view('pages.listings', compact('listings', 'headline')); 

    } 

這裏是我的評論表:

Review table for listing

回答

1

這是我做過什麼:

public function mostReviews() { 

    $reviews = DB::table('reviews') 
     ->select(DB::raw('AVG(stars) as review_score, listing_id')) 
     ->groupBy('listing_id') 
     ->orderBy('review_score', 'desc') 
     ->limit(10) 
     ->get(); 

    foreach($reviews as $key => $review) { 
    $reviews[$key] = Listing::find($review->listing_id); 
    } 

    return view('listings.most-reviews', [ 
    'listings' => $reviews 
    ]); 

} 
0

下應該工作

$listing = Listing::with('reviews')->orderByRaw(function($listing) 
{ 
    return $listing->review->count(); 
}, desc)->take(10)->get(); 
+0

這可能會實現,但我需要每個崗位大多數評論排序,從最高到最低。目前沒有顯示任何東西。 – David

+0

嘗試添加' - >獲得()''後取(10)' – xhulio

+0

它給我這個錯誤:**用strtolower()預計參數1是字符串,對象給予** – David

0

在上市模型試試這個

$review = Review::orderBy('-- most reviews here --'); 
$reviewCount = $review->count(); 
$listings=$review->take(10)->get(); 
0

:在你的看法

public function countReview() { 
    return count($this->reviews); 
    } 

{{$listing->countReview()}} 

也許在控制器,你可以寫的財產以後,如:

public function mostReviews() { 
    Review::orderBy('listing', 'desc')->blahblah; // or 'asc' 
} 
+0

哪裏是$這個 - >產品來自哪裏? – David

+0

將該代碼放入您的列表模型中,我製作了自定義函數來計算評論。對不起,我忘了chenge吧,我是從我的項目 – Robin

+0

我用我的當前項目的代碼複製代碼和它的工作原理 – Robin

1

我沒有測試過,但下面的查詢(使用查詢生成器)應該給你你想要的東西 - 10家上市與大多數評論。另外average_stars列應該返回平均星號率。您可以輕鬆地修改查詢通過改變orderByaverage_stars得到10個收視率最高的物品。

$listings = \DB::table('reviews AS r') 
    ->select([ 
    'r.listing_id', 
    \DB::raw('COUNT(*) AS no_of_reviews'), 
    \DB::raw('AVG(r.stars) AS average_stars'), 
    'l.*']) 
    ->join('listings AS l', 'l.id', '=', 'r.listing_id') 
    ->limit(10) 
    ->orderBy('no_of_reviews', 'DESC') 
    ->groupBy('listing_id') 
    ->get(); 

請注意版本高達版本5.2的Laravel這將返回數組stdObject。您可以使用與Eloquent Collection相似的方式輕鬆訪問刀片模板中的那些模板。

@foreach($listings as $listing) 
<tr> 
    <td>{{ $listing->id }}</td> 
    <td>{{ $listing->title }}</td> 
    <td>{{ $listing->no_of_reviews }}</td> 
    <td>{{ floor($listing->average_stars) }}</td> 
</tr> 
@endforeach