简体   繁体   English

Laravel Eloquent如何加入查询而不是表?

[英]Laravel Eloquent how to join on a query rather than a table?

I want to achieve this in Laravel: 我想在Laravel实现这个目标:

SELECT * FROM products JOIN
(SELECT product_id, MIN(price) AS lowest FROM prices GROUP BY product_id) AS q1
ON products.id = q1.product_id
ORDER BY q1.lowest;

I wrote this, but clearly there is something wrong: 我写了这个,但显然有一些错误:

$products = new Product();
$products = $products->join(
    Price::whereNotNull('price')->select('product_id', DB::raw('min(price) as lowest'))->groupBy('product_id'), 'products.id', '=', 'product_id'
    )->orderBy('lowest')->get();

The error I got: 我得到的错误:

ErrorException in Grammar.php line 39:
Object of class Illuminate\Database\Eloquent\Builder could not be converted to string.

I'm currently using join(DB::raw('(SELECT product_id, MIN(price) AS lowest FROM prices WHERE price IS NOT NULL GROUP BY product_id) AS q1'), 'products.id', '=', 'q1.product_id') as a workaround. 我目前正在使用join(DB::raw('(SELECT product_id, MIN(price) AS lowest FROM prices WHERE price IS NOT NULL GROUP BY product_id) AS q1'), 'products.id', '=', 'q1.product_id')作为一种解决方法。 Just wondering how to do this in the Eloquent way? 只是想知道如何以雄辩的方式做到这一点? Thanks. 谢谢。

If you want to make a single query for efficiency reasons in this case Eloquent is not going to help you much, it is possible but is a hassle. 如果你想在这种情况下出于效率原因进行单一查询,那么Eloquent对你没什么帮助,这是可能的,但是很麻烦。 For cases like this you have QueryBuilder. 对于这样的情况,你有QueryBuilder。

DB::table('products')
    ->join(
        DB::raw('(SELECT product_id, MIN(price) AS lowest FROM prices GROUP BY product_id) AS q1'),
        'products.id', '=', 'q1.product_id'
    )
    ->orderBy('q1.lowest')->get();

If you change get() for getSql() you get the following 如果更改getSql() get()getSql()得到以下结果

select * from `products` inner join
(SELECT product_id, MIN(price) AS lowest FROM prices GROUP BY product_id) AS q1
on `products`.`id` = `q1`.`product_id` order by `q1`.`lowest` asc

Unfortunately as far as I know you can't use a subquery without DB::raw, nevertheless it is not insecure as long as you don't put user input in the query. 不幸的是,据我所知你不能使用没有DB :: raw的子查询,但只要你不在查询中输入用户输入它就不是不安全的。 Even in that case you can use it securely by using PDO. 即使在这种情况下,您也可以使用PDO安全地使用它。

As for Eloquent, your product model doesn't even have a price field (it probably has a prices() function returning a relationship object) so it makes no sense to get a Product model with a single price asociated to it. 至于Eloquent,你的产品模型甚至没有price字段(它可能有一个返回关系对象的prices()函数)所以获得一个与之相关的单一价格的Product模型是没有意义的。

Edit: 编辑:

You can also eager load the relationship, ie (assuming you have the model relationship set as Trong Lam Phan's example) 您也可以急切地加载关系,即(假设您将模型关系设置为Trong Lam Phan的示例)

$products = Product::with('prices')->get();
foreach ($products as $product)
{
    $minPrice = $product->prices->min('price');
    // Do something with $product and $minPrice
}

This will only run a single query but the min() operation is not done by the database. 这只会运行一个查询,但min()操作不是由数据库完成的。

In Eloquent, follow me, you need to think a little bit differently from normal mysql query. 在Eloquent中,请关注我,您需要与普通的mysql查询略有不同。 Use Model instead of complicated query. 使用Model而不是复杂的查询。

First of all, you need to create Product and Price models with relationship between them: 首先,您需要创建具有它们之间关系的Product和Price模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    public function prices()
    {
        return $this->hasMany('\App\Price');
    }
} 

class Price extends Model
{
    public function product()
    {
        return $this->belongsTo('\App\Product');
    }
}

Then, you need to select all products: 然后,您需要选择所有产品:

$products = \App\Product::get();
foreach ($products as $product)
{
    $minPrice = $product->prices->min('price');
    echo 'Min price of product ' . $product->name . ' is: ' . $minPrice;
}

EDIT 编辑

If you have a problem with the performance, just get the product's id. 如果您遇到性能问题,只需获取产品ID即可。

$products = \App\Product::get(['id']);

If you don't like this way of Eloquent, you may use Query Builder like that: 如果你不喜欢这种Eloquent方式,你可以像这样使用Query Builder:

$result = \App\Price::join('products', 'prices.product_id', '=', 'products.id')
                ->select('product_id', 'name', \DB::raw("MIN(price) AS min_price"))
                ->groupBy('product_id')
                ->orderBy('min_price')
                ->get();

or you can do like that: 或者你可以这样做:

\App\Price::join('products', 'prices.product_id', '=', 'products.id')
        ->selectRaw("name, MIN(price) AS min_price")
        ->groupBy('product_id')
        ->orderBy('min_price')
        ->get()

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

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