There is such a structure: enter image description here

How can I choose for a set of id-cars their type.id, type.name, type.price Only type.price for all cars of the same type should be summed up.

My option does not work:

Carriage::with('type') ->whereIn('id', [1,2,3]) ->select('types.id', 'types.name', 'types.price') ->groupBy('types.id') ->get(); 

Carriage Model:

 <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class Carriage * @package App\Models */ class Carriage extends Model { /** * @return mixed */ public function type() { return $this->belongsTo(Type::class); } } 

Model Type:

 <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * Class Type * @package App\Models */ class Type extends Model { /** * @return mixed */ public function carriages() { return $this->hasMany(Carriage::class); } } 
  • Give the models for both tables - Maxim Stepanov

1 answer 1

Try this:

 Type::select('id', 'name') ->selectRaw('sum(price) as sum_price') ->whereHas('carriages', function($query) { $query->whereIn('id', [1,2,3]); }) ->groupBy('id, name') ->get();