LoginSignup
2
1

More than 3 years have passed since last update.

laravel クエリビルダ プレーンなselect文でカラム同士の足し算

Last updated at Posted at 2020-02-17

こんにちは!

lravelでカラム同士の足し算がしたくていろいろやったけどうまくいかず、リファレンスを読んだところ便利なクエリビルダの方法があったので紹介します!

laravel6.x系です
紹介するコードを参考にするのであれば、データベースに対応するモデルが作成済みであることを前提とします!

〇〇Repository.php
<?php

namespace App\Repositories\Cost;

use App\Models\Cost;
use Illuminate\Support\Facades\DB;

class CostRepository implements CostRepositoryInterface
{
    protected $cost;

    public function __construct(Cost $cost)
    {
        $this->cost = $cost;
    }

    /**
     * ユーザーの全ての情報+spendingの合計をゲット
     */
    public function getAllRecordByUser($user_id)
    {
        return $this->cost->select(DB::raw(' *, morning_spending + daytime_spending + night_spending AS spending_all'))->where('user_id', '=', $user_id)->get();

    }
}

ファイルはRepositoryですが、基本ファサードのDBをuseすればコントローラとかでも使えるはず

select(DB::raw('この中に記述したいselect文を記載'))

こうするとプレーンなsqlのselect文を記載することができます!

このクエリビルダで得られるsql文は

"select  *, morning_spending + daytime_spending + night_spending AS spending_all from `costs` where `user_id` = ?"

こんな感じになります

上のコードで得られるテーブル構造はuser_idカラムが引数で渡したuser_idの

colmun1 colmun2 mroning_spending daytime_spending night_spending spending_all
*** *** 100 200 300 600

のようなテーブル構造を得られます!

laravel使い始めてまだまもないですが、sqlベースで手っ取り早く値を取得したいときはプレーンなsql文を書いた方が楽ですね!

まぁ、クエリビルダをもっと勉強すれば、多分プレーンなsql文を書かなくてもできると思うのですが・・・

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1