Question

I am attempting to do the equivalent of this:

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

Here is where I am at now, but it of course doesn't work:

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));

}

I don't really see anything in the docs on how to do this, and I can't seem to piece it together from other posts.

In "regular" SQL, the subquery is treated AS a column, but I am not sure how to string that together here. Thanks for any help on this.

Was it helpful?

Solution

I strongly recommend you to use Eloquent, instead of pure SQL. It's one of the most beautful things in Laravel. Two models and relations and it's done! If you need to use pure SQL like that, put it all in DB::raw. It's easier, simpler and (ironically) less messy!

With the models, you could use relations between the two tables (represented by the models itself) and say (so far I understood) that Brands belongs to Products, and Images belongs to Product. Take a look at Eloquent's documentation on Laravel. Probably will be more clearly.

Once the relations are done, you can only say that you wanna get

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

That and a better look at Eloquent's documentation should help you to do the job.

P.S.: I didn't test the code before send it and wrote it by head, but i think it works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top