繁体   English   中英

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。 这是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:我没有在发送之前测试代码并按头编写,但我认为它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM