【问题标题】:Laravel, make nested SQL query with inner join on Eloquent and Laravel's ModelsLaravel,在 Eloquent 和 Laravel 的模型上使用内连接进行嵌套 SQL 查询
【发布时间】:2018-12-25 05:37:34
【问题描述】:

我有以下数据库:

简单来说,用户有很多店铺,店铺有很多产品等等。 我需要在 Eloquent ORM 的帮助下进行这个查询:

SELECT * FROM tmp.shops
INNER JOIN
    (SELECT * FROM tmp.products
    WHERE tmp.products.shop_id IN
    (SELECT id FROM shops where user_id = 1))  as nested_query
ON  tmp.shops.id = nested_query.shop_id;

我需要获取用户店铺中每个产品的信息和店铺信息。

关于我的模型。这是与用户模型中的 Shop 的关系

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function shop()
{
    return $this->hasMany('App\Shop');
}

这是 Shop 模型中的关系:

public function user()
{
    return $this->belongsTo('App\User');
}

public function products()
{
    return $this->hasMany('App\Product');
}

最后,产品型号:

public function shop()
{
    return $this->belongsTo('App\Shop');
}

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    急切地加载您在产品模型中定义的商店关系(with('shop')

    $user_id=1;
    $products = Product::with('shop')
                       ->whereHas('shop.user', function ($query) use($user_id) {
                            $query->where('id', '=', $user_id);
                        })
                       ->get();
    

    型号

    class Product extends Model {
    
        public function shop() {
            return $this->belongsTo('Shop', 'shop_id');
        }
    }
    
    class Shop extends Model {
        public function user() {
            return $this->belongsTo('User', 'user_id');
        }
        public function products() {
            return $this->hasMany('Product', 'shop_id');
        }
    }
    

    现在,当您迭代 products 时,您将在每个产品对象中获得商店详细信息对象

    【讨论】:

    • 您建议将此代码添加到产品模型中。我对吗? $user_id=1; $products = Product::with('shop') ->whereHas('shop.user', function ($query) use($user_id) { $query->where('id', '=', $user_id) ; }) ->get();
    • @Aleksej_Shherbak 不,您的模型看起来不错,您可以在控制器中使用查询生成器代码,请参阅eager loading 以获得更好的说明
    • 成功了!!!!!!是工作! ))) 我明白了,一点点,但是明白!!!谢谢你。当你这样建议我时,我一直在考虑制作嵌套循环!
    • 看来你是Eloquent的大师
    猜你喜欢
    • 2015-06-27
    • 2015-08-19
    • 1970-01-01
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    相关资源
    最近更新 更多