Есть вот такая структура:
Как можно выбрать для набора id-вагонов их type.id, type.name, type.price Только type.price для всех вагонов одного типа суммировать.
Мой вариант не работает:
Carriage::with('type')
->whereIn('id', [1,2,3])
->select('types.id', 'types.name', 'types.price')
->groupBy('types.id')
->get();
Модель Carriage:
<?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);
}
}
Модель 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);
}
}
Попробуйте так:
Type::select('id', 'name')
->selectRaw('sum(price) as sum_price')
->whereHas('carriages', function($query) {
$query->whereIn('id', [1,2,3]);
})
->groupBy('id, name')
->get();
Продвижение своими сайтами как стратегия роста и независимости