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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3