我想知道如何使用雄辩的ORM来计算收入。
挑战: 计算每个客户的计划收入。每个客户都有很多项目。
问题: 如何进行"预算成本"等操作?在SQL之外。我可以把它放到我的模型或其他地方来访问这些"特殊"在我看来属性?
这段代码很有效,但我觉得不是很优雅。
$planned_clients = DB::table('clients')
->join('projects', 'clients.id', '=', 'projects.client_id')
->select('projects.*', 'clients.title as client_title',
DB::raw('SUM(projects.planned_budget) as planned_budget'),
DB::raw('SUM(projects.planned_costs) as planned_costs'),
DB::raw('SUM(projects.planned_budget) - SUM(projects.planned_costs) as total_revenue')
)
->where('projects.commitment', '=', Project::PLANNED)
->whereNotIn('projects.status', [Project::CANCELED])
->groupBy('projects.client_id')
->get();
以下是架构
class CreateClientsTable extends Migration {
public function up()
{
Schema::create('clients', function(Blueprint $table) {
$table->increments('id');
$table->string('client_id')->unique();
$table->string('title')->unique();
$table->boolean('is_keyclient')->default(0);
$table->text('comment');
$table->timestamps();
});
}
}
class CreateProjectsTable extends Migration {
public function up()
{
Schema::create('projects', function(Blueprint $table) {
$table->increments('id');
$table->string('project_id')->unique();
$table->string('title');
$table->integer('client_id')->unsigned();
$table->enum('commitment', array('save', 'planned'));
$table->enum('status', array('waiting', 'running', 'done', 'canceled', 'cleared'));
$table->string('comment');
$table->integer('planned_budget');
$table->integer('planned_costs');
$table->integer('actual_budget');
$table->integer('actual_costs');
$table->timestamps();
});
Schema::table('projects', function(Blueprint $table) {
$table->foreign('client_id')->references('id')->on('clients');
});
}