简体   繁体   中英

Laravel has many and grouping

I can't seem to get the syntax right for this query.

Basically, I have a product that is listed, where an offer is made by a user:

So in Offer.php

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

And in User.php

public function offers()
{
    return $this->hasMany('App\Offer', 'buyer_id');
}

Then in Product.php

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

I need to group offers by the user that has made them, and then group that again by the category of the product the offer is against.

Does anyone have ideas where I can start to group these correctly?

Try with Query Builder . Like this ( I don't know your tables`s structure):

 $offers = DB::table('offers')
             ->joinLeft('users','users.id','=','offers.buyer_id')
             ->joinLeft('products','products.id','=','offers.product_id')
             ->groupBY('users.id','products.category_id')
             ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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