3

我正在尝试做与此等效的事情:

select p.id, p.title, b.brand, 
(select big from images where images.product_id = p.id order by id asc limit 1) as image 
from products p

inner join brands b on b.id = p.brand_id

这是我现在所在的位置,但它当然不起作用:

public function getProducts($brand)
{
    // the fields we want back
    $fields = array('p.id', 'p.title', 'p.msrp', 'b.brand', 'p.image');

    // if logged in add more fields
    if(Auth::check())
    {   
        array_push($fields, 'p.price_dealer');
    }

    $products = DB::table('products as p')
        ->join('brands as b', 'b.id', '=', 'p.brand_id')
        ->select(DB::raw('(select big from images i order by id asc limit 1) AS image'), 'i.id', '=', 'p.id')
        ->where('b.active', '=', 1)
        ->where('p.display', '=', 1)
        ->where('b.brand', '=', $brand)
        ->select($fields)
        ->get();

    return Response::json(array('products' => $products));

}

我真的没有在文档中看到有关如何执行此操作的任何内容,而且我似乎无法从其他帖子中将其拼凑起来。

在“常规”SQL 中,子查询被视为一列,但我不知道如何在这里将它们串在一起。感谢您对此的任何帮助。

4

1 回答 1

1

强烈推荐你使用 Eloquent,而不是纯 SQL。这是 Laravel 中最漂亮的东西之一。两个模型和关系就完成了!如果你需要像那样使用纯 SQL,把它全部放在DB::raw. 它更容易,更简单并且(具有讽刺意味的是)不那么混乱!

使用模型,您可以使用两个表之间的关系(由模型本身表示)并说(到目前为止我理解)Brands属于Products,并且Images属于Product。查看Eloquent 在 Laravel 上文档。可能会更清楚。

一旦关系完成,你只能说你想得到

$product = Product::where(function ($query) use ($brand){
                      $brand_id = Brand::where('brand', '=', $brand)->first()->id;
                      $query->where('brand_id', '=', $brand_id);
                  })
                  ->image()
                  ->get();

那以及更好地查看 Eloquent 的文档应该可以帮助您完成这项工作。

PS:我在发送之前没有测试代码并写了它,但我认为它有效。

于 2013-10-27T05:10:45.303 回答