rc.adhikari
rc.adhikari

Reputation: 2222

How to create the migrations for database views using php artisan in Laravel?

Actually, I have managed to create a sql views for Laravel using PHP Artisan using below step.

Step 1. Run below command:

php artisan make:migration create_overall_report_views

Step 2.

Open the migration file and add the below code:

class CreateOverallReportView extends Migration 
{
  /**
  * Run the migrations.
  *
  * @return void
  */
  public function up()
  {
    //
    DB::statement("
      CREATE VIEW views_overall_report AS
      (
        SELECT er.user_id as user_id, e.id AS entities_id, 
            c.status_id AS status_id, s.name AS status_name

        FROM `user_roles` er
          LEFT JOIN elists e ON e.id=er.entities_id
          LEFT JOIN `clists` c ON c.id=e.checklists_id
          LEFT JOIN `status` s ON s.id = c.overall_status_id

        WHERE s.slug = 'completed'
          AND c.deleted_at IS NULL
      )
    ");
  }

  /**
  * Reverse the migrations.
  *
  * @return void
  */
  public function down()
  {
    DB::statement('DROP VIEW IF EXISTS views_overall_report');
  }  

}

Step 3. To call and run the SQL Views via Laravel query

$items = $DB::table('views_overall_report')
            ->select('status_id', 'status_name',
                $DB::raw('count(entities_id) as counts')
            )
            ->groupBy('status_id')
            ->orderBy('counts' , 'desc')
            ->whereIn('user_id', Auth::user()->id())
            ->get();
print_r($items);

Hope that helps. Please let me know if anyone has better solution!!

Upvotes: 49

Views: 61459

Answers (5)

Peon
Peon

Reputation: 8020

Stumbled on the same issue and found the solution @ http://programmingarehard.com/2013/11/10/eloquent_and_views.html/

class CreateCompaniesView extends Migration 
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        DB::statement("CREATE VIEW companiesView AS
                        SELECT *,
                        (
                            SELECT GROUP_CONCAT(DISTINCT id SEPARATOR ',')
                            FROM people AS p
                            WHERE p.company_id = c.id
                        ) AS person_ids
                        FROM companies AS c");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        DB::statement("DROP VIEW companiesView");
    }
}

Upvotes: 59

Márcio Carvalho
Márcio Carvalho

Reputation: 51

You can do this:

public function up()
{
  DB::statement($this->dropView());
  DB::statement($this->createView());
}

private function dropView(): string
{
   return <<<SQL
   DROP VIEW IF EXISTS `meter_reading_reports`;
   SQL;
}

private function createView(): string
{
   return <<<SQL
   CREATE VIEW `meter_reading_reports` AS
   SELECT /* … The query */
   SQL;
}

Now that we have a migration in place, all else just works like normal Laravel!

class MeterReadingReport extends Model
{
   protected $casts = [
      'day' => 'date',
   ];
   public function unit(): BelongsTo
   {
      return $this->belongsTo(Unit::class);
   }

   public function user(): BelongsTo
   {
      return $this->belongsTo(User::class);
   }
}

Refer: https://stitcher.io/blog/eloquent-mysql-views

Upvotes: 5

Ayman Elshehawy
Ayman Elshehawy

Reputation: 2964

Write your migration like this, with 'CREATE OR REPLACE' in up function:

public function up()
   {

    DB::statement('CREATE OR REPLACE VIEW my_view AS SELECT name FROM users');
   }

public function down()
    {
        DB::statement('DROP VIEW my_view');
    }

Upvotes: 4

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

I've created a package for creating, renaming and dropping views:
https://github.com/staudenmeir/laravel-migration-views

You can provide a query builder instance or an SQL string:

use Staudenmeir\LaravelMigrationViews\Facades\Schema;

class CreateOverallReportView extends Migration 
{
    public function up()
    {
        $query = DB::table('user_roles as er')->[...];
        $query = 'SELECT [...] FROM `user_roles` er [...]';

        Schema::createView('views_overall_report', $query);
    }

    public function down()
    {
        Schema::dropView('views_overall_report');
    }  
}

Upvotes: 5

julian martinez
julian martinez

Reputation: 11

You can also try this DB::connection()->getPdo()->exec("your sql query"); it works

class CreateCompaniesView extends Migration 
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            DB::connection()->getPdo()->exec("CREATE VIEW companie ...");
        }

        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            DB::connection()->getPdo()->exec("DROP VIEW companies ...");
        }
    }

Upvotes: 1

Related Questions