将SQL查询转换为Laravel 4 Eloquent

时间:2014-12-26 20:43:42

标签: sql laravel laravel-4 eloquent

任何人都可以帮我将以下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();

1 个答案:

答案 0 :(得分:0)

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

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