duanbodai5166 2013-10-27 00:13
浏览 115
已采纳

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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程