Laravel,在Eloquent和Laravel的模型上使用内部联接进行嵌套SQL查询

时间:2018-07-17 13:31:42

标签: laravel eloquent

我有以下数据库:

enter image description here

enter image description here

简单来说,用户有很多商店,商店有很多产品等。 我需要借助雄辩的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;

我需要在用户商店中获取有关每种产品的信息以及关于商店的信息。

关于我的模特。这与用户模型中的商店有关

/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function shop()
{
    return $this->hasMany('App\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');
}

1 个答案:

答案 0 :(得分: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时,将在每个产品对象中获得商店详细信息对象

相关问题