duanbodai5166
2013-10-27 00:13 阅读 79
已采纳

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

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    doufu7835 doufu7835 2013-10-27 05:10

    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.

    点赞 6 评论 复制链接分享

相关推荐