我是Laravel的新手,如何使用Laravel Eloquent执行以下mysql查询。
SELECT p.*,
(
SELECT COUNT(*) FROM product_images AS pi WHERE pi.productID = p.productID
)AS totalImages
FROM products AS p
答案 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();