Laravel显示类别计数不显示

时间:2017-09-21 07:30:23

标签: php mysql laravel

我在Laravel 5.5中有一个侧边栏菜单,我希望显示具有更多ID的类别计数,但它们不显示任何结果。

我的代码:

<?php
$count = DB::select('select category_id from products where category_id = :id', ['id' => 1]);
?>

如何选择更多ID?示例where category_id = 1 and 2

我现在尝试了一个星期,我希望有人可以在这里帮助我。

我的php代码可以工作,但不是laravel;)

<?php
$con=mysqli_connect("host","username","password","database");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT category_id FROM products WHERE category_id = 2";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

2 个答案:

答案 0 :(得分:0)

您可以尝试

/[0-9A-Z]+(-[0-9A-Z]+)+/

答案 1 :(得分:0)

DB::select()会返回一系列结果,因此您可以计算结果:

$count = count(DB::select('select category_id from products where category_id = :id', ['id' => 1]));

但是,您可能更喜欢使用query builder and the count() aggregate function

$count = DB::table('products')->whereIn('category_id', [1])->count();

这允许您传递多个category_ids,如下所示:

$count = DB::table('products')->whereIn('category_id', [1, 2, 3])->count();