如何在Laravel中使用子查询计算产品图像

时间:2015-02-14 15:51:11

标签: mysql laravel laravel-4 eloquent

我是Laravel的新手,如何使用Laravel Eloquent执行以下mysql查询。

SELECT p.*, 
(
    SELECT COUNT(*) FROM product_images AS pi WHERE pi.productID = p.productID
)AS totalImages
FROM products AS p 

1 个答案:

答案 0 :(得分:1)

您可以使用DB::raw在select:

中注入子查询
Product::from('products p')
    ->select(DB::raw('p.*, (SELECT COUNT(*) FROM product_images AS pi WHERE pi.productID = p.productID) AS totalImages'));

还可以选择在Product模型与Image模型之间设置one-to-many关系:

class Product extends Eloquent {

    public function images()
    {
        return $this->hasMany('Image');
    }

}

之后你可以像这样获取图像数:

Product::find($productId)->images()->count();