Laravel 4从子查询中的另一个表中选择列

时间:2013-10-27 00:13:06

标签: php mysql laravel laravel-4 fluent

我试图做相同的事情:

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中,子查询被视为一列,但我不知道如何将它们串在一起。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

强烈建议您使用Eloquent,而不是纯SQL。这是Laravel最漂亮的东西之一。两个模型和关系,它已经完成!如果您需要像这样使用纯SQL,请将其全部放在DB::raw中。它更容易,更简单,而且(讽刺的是)不那么混乱!

使用模型,您可以使用两个表之间的关系(由模型本身表示)并说(到目前为止我理解)品牌属于产品,和图像属于产品。请查看Laravel上的Eloquent's文档。可能会更清楚。

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

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

更好地了解Eloquent的文档可以帮助您完成这项工作。

P.S。:在发送代码之前我没有对代码进行测试并按头编写,但我认为它有效。

相关问题