【问题标题】:Variable inside laravel query builder is always nulllaravel 查询生成器中的变量始终为空
【发布时间】:2021-04-20 02:49:55
【问题描述】:

我试图找到以这种方式评论产品的用户:

public function getUserToRate(Product $product)
{
    $userIds = DB::table('product_ratings')->where('product_id', $product->id)->pluck('user_id');

    return $userIds;
}

但问题是 $product->id 为空。如果我这样做,就会出现这样的结果:

DB::table('product_ratings')->where('product_id', $product->id)->toSql():
select * from `product_ratings` where `product_id` = ?

为什么我的$product->id 为空?我已经检查并且模型存在,但我似乎无法在查询生成器中使用它。

谁能帮帮我?谢谢

【问题讨论】:

  • 你怎么会认为是null
  • 因为在查询中它被标记为 ' ? ' 所以我假设它是一个空值,不是吗?
  • 不是,是prepared statement的参数,sql语句和它的参数是分开发送到数据库的....查看“prepared statements”

标签: laravel laravel-query-builder


【解决方案1】:

我认为您不需要产品模型。所以忽略像 Product $product 这样的路由模型绑定。相反,您可以使用您的 $oroductId。并像这样查询 UserId:

public function getUserToRate( $productId)
{
    $userIds = ProductRating::where('product_id', $productId)->pluck('user_id');

    return $userIds;
}

    

【讨论】:

  • 我已经尝试过这样但它无论如何都不起作用,查询仍然看起来像这样:select * from product_ratings where product_id = ?
  • 我可以看看你的路线到达这个函数吗?还有你调用那个路线的代码
猜你喜欢
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 2018-05-16
  • 2017-01-30
  • 2023-01-14
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多