Laravel, make nested SQL query with inner join on Eloquent and Laravel's Models

吃可爱长大的小学妹 提交于 2019-12-24 10:45:21

问题


I have followng database:

Simply speaking, Users have many shops, Shops have many products etc. I need to make this query with the help of 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;

I need to catch information about each product in user's shop and info about shop.

About my Models. This is relation with Shop in User model

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

And this is Relations in Shop model:

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

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

Finaly, Product model:

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

回答1:


Eager load your shop's relation(with('shop')) defined in your product's model as

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

Models

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');
    }
}

Now when you iterate products you will get shop details object in each product object



来源:https://stackoverflow.com/questions/51382715/laravel-make-nested-sql-query-with-inner-join-on-eloquent-and-laravels-models

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!