【问题标题】:Laravel 4 select column from another table in subqueryLaravel 4 从子查询中的另一个表中选择列
【发布时间】:2013-11-05 22:58:04
【问题描述】:

我正在尝试做类似的事情:

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

【问题讨论】:

    标签: php mysql laravel laravel-4 fluent


    【解决方案1】:

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

    使用模型,您可以使用两个表之间的关系(由模型本身表示)并说(目前我理解)Brands 属于 ProductsImages 属于 Product。查看 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.:我在发送之前没有测试代码并直接编写,但我认为它有效。

    【讨论】:

    • 那么$query 变量从何而来? ;)
    猜你喜欢
    • 1970-01-01
    • 2022-11-28
    • 2017-10-05
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2010-12-25
    相关资源
    最近更新 更多