计算Laravel中查询的位置

时间:2017-05-15 15:07:41

标签: mysql laravel laravel-5

我在这里有一个问题,我没有解决。 我正在尝试在Laravel中查询,我需要计算企业有多少优惠,以显示商家ID,商家和商家名称的总优惠。

$business_offers = DB::table('offers')
        ->join('businesses', 'offers.id_business', '=', 'businesses.id')
        ->select(['businesses.id', 'businesses.name', DB::raw('count(offers.id) as total_offers')])
        ->orderby('total_offers', 'DESC')
        ->get();

但它没有以这种方式工作。我也在mysql中完成了查询,但无法将其集成到Laravel中。

SELECT bu.id,(SELECT count(of.id) from offers of where of.id_business = bu.id )
 as total_offers, bu.`name` from businesses bu ORDER BY total_offers DESC

提前致谢

2 个答案:

答案 0 :(得分:0)

如果您设置了模型和关系,它应该像以下一样简单:

$businesses = Business::withCount(['offers'])->get;

foreach ($businesses as $business) {
    echo $business->offers_count;
}

来自Laravel documentation

  

如果您想计算没有关系的结果数   实际加载它们你可以使用withCount方法,这将   在结果模型上放置{relation} _count列。

您的商业模式中所需要的只是:

class Business extends Model
{
    /**
     * Get all of the offers for the business.
     */
    public function offers()
    {
        return $this->hasMany('App\Offer');
    }
}

并在Offer模型中:

class Offer extends Model
{
    /**
     * Get the business for the current offer.
     */
    public function business()
    {
        return $this->belongsTo('App\Business', 'business_id');

    }
}

答案 1 :(得分:0)

从字面上读它可能会起到以下作用:

$business_offers = DB::table('businesses bu')
    ->select(['bu.id', DB::raw("(SELECT count(of.id) from offers of where of.id_business = bu.id )") ,'bu.name'])
    ->orderBy('total_offers', 'DESC')
    ->get();

如果你想要它更高效(也许):

$business_offers = DB::table('offers')
    ->join('businesses', 'offers.id_business', '=', 'businesses.id')
    ->select(['businesses.id', DB::raw("COUNT(1) as total_offers"),'businesses.name'])
    ->groupBy("businesses.id","businesses.name")
    ->orderBy('total_offers', 'DESC')
    ->get();