簡體   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