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


Laravel 4 select column from another table in subquery

我正在尝试做这个等效的事情:

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中,子查询被视为一列,但我不确定如何在此处将其串在一起。感谢您对此的任何帮助。

强烈建议您使用Eloquent,而不是纯SQL。这是拉拉维尔最美丽的事情之一。两个模型和关系就完成了!如果您需要像这样使用纯 SQL,请将其全部放在 DB::raw 中。它更容易,更简单,而且(具有讽刺意味的是)不那么混乱!

对于模型,

您可以使用两个表之间的关系(由模型本身表示)并说(到目前为止我理解)品牌属于产品,图像属于产品看看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:我在发送之前没有测试代码并按头编写,但我认为它有效。

相关文章: