简体   繁体   English

Laravel中的MySQL子查询,如何联接查询并将第二查询的结果作为新列添加到第一查询?

[英]MySQL sub query in Laravel, how to join queries and add second query's result as a new column to first query?

I have two tables: 我有两个表:

- PRODUCTS (having: ID, NAME, PRICE)
- LIKES (having: ID, PRODID, NAME)

I would like to query the first table while counting (and returning as a new column) in a sub query all the likes the product has. 我想查询第一个表,同时在子查询中计数(并返回为新列)该产品具有的所有赞。 How could I combine the following queries? 如何合并以下查询?

$products = DB::table('PRODUCTS')
                  ->get();

$likes = DB::table('LIKES')
                  ->select(DB::raw('count(*) as total'))
                  ->where('PRODID', '=', 'product id from first table')
                  ->get();

How could I achieve this using Laravel queries? 如何使用Laravel查询实现这一目标? Thanks! 谢谢!

Not the answer you specifically asked for but as an alternative, this would be extremely easy to handle with Eloquent. 这不是您明确要求的答案,但是作为替代,使用Eloquent非常容易处理。

$products = Product::with('likes');
foreach ($products as $product) {
    echo 'Number of likes: '.$product->likes->count();
}

Use a join with a group by clause, rather than a subquery. 使用带有group by子句的联接,而不是子查询。 This way you can get the counts for all products in one go, you do not have to query the counts one by one. 这样,您可以一次获得所有产品的计数,而不必一一查询。 The sql looks like as follows: sql如下所示:

select p.id, p.name, p.price, count(l.id) as likecount
from products p
left join likes l on p.id=l.prodid
group by p.id, p.name, p.price

Try like this 这样尝试

$likes = DB::table('LIKES')
      ->join('PRODUCTS', 'LIKES.PRODID', '=', 'PRODUCTS.id') 
      ->select('LIKES.*') 
      ->where('PRODUCTS.id', '=', 3)      
      ->get();
$total_like = count($likes); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM