【问题标题】:Convert SQL query into Laravel 4 Eloquent将 SQL 查询转换为 Laravel 4 Eloquent
【发布时间】:2015-02-24 00:57:56
【问题描述】:

谁能帮我把下面的 SQL 查询转换成 Eloquent?

select * 
from products, categories 
where products.productID=categories.productID and categories.categoryID = 5;

这是我尝试过的:

$products = DB::table('products') ->join('categories', function($join) {
    $join->on('products.productID', '=', 'categories.productID')
         ->where('categories.categoryID',$categoryID)
} ->get();

【问题讨论】:

  • 您是否设置了 Eloquent 模型和关系?另外,您尝试过什么?
  • 我没有模型设置。我正在连接到现有数据库。我试过这个。 $products = DB::table('products') ->join('categories', function($join) { $join->on('products.productID', '=', 'categories.productID') -> where('categories.categoryID',$categoryID) } ->get();
  • 其他仅使用产品或类别的查询都有效。

标签: sql laravel laravel-4 eloquent


【解决方案1】:

问题可能是,$categoryID 在闭包(又名匿名函数)内不可用。为了能够“从外部”使用变量,您必须添加 use

$products = DB::table('products')->join('categories', function($join) use ($categoryID){
$join->on('products.productID', '=', 'categories.productID')
     ->where('categories.categoryID', '=', $categoryID);
})->get();

【讨论】:

  • 当我尝试更改时,我仍然遇到错误。 production.ERROR:异常 'Symfony\Component\Debug\Exception\FatalErrorException' 与消息 '语法错误,意外 '->' (T_OBJECT_OPERATOR)' 在 /test/app/storage/views/10ada48a3235fc816bfdf5ca4f491459:33 堆栈跟踪:#0 [内部函数]: Illuminate\Exception\Handler->handleShutdown() #1 {main} [] []
  • ->get() 之前缺少一个 )。我更正我的答案
  • where on JoinClause 类需要所有 3 个参数,您不能省略运算符 =
  • 没错,因为它基本上是on 的别名。谢谢@JarekTkaczyk
猜你喜欢
  • 2020-10-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-31
相关资源
最近更新 更多