Tuesday 29 March 2016

Create the migrations for database views using php artisan in Laravel

Please follow the steps to create a sql views for Laravel using PHP Artisan using below step.

Step 1. Run below command:
php artisan make:migration create__views

Step 2. Open the migration file and add the below code:
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
     //
     DB::statement("
      CREATE VIEW views_overall_status AS
      (
       SELECT er.id AS auth_users_entity_roles_id, er.auth_users_id,
        e.checklists_id, c.overall_status_id AS status_id, s.name AS status_name
       
       FROM `auth_users_entity_roles` er
        LEFT JOIN entities e ON e.id=er.entities_id
        LEFT JOIN `checklists` c ON c.id=e.checklists_id
        LEFT JOIN `status` s ON s.id = c.overall_status_id
        
       WHERE s.slug = 'operating_risks' AND e.deleted_at IS NULL
        AND c.deleted_at IS NULL
      )
     ");
    }
    
    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
     //
     DB::statement('DROP VIEW IF EXISTS views_overall_status');
    }

Step 3. To call and run the SQL Views via Laravel query
    $items = $DB::table('views_entities_by_overall_status')
                ->select('status_id', 'status_name', 'status_name_trans_text_id',
                    $DB::raw('count(entities_id) as counts')
                )
                ->groupBy('status_id')
                ->orderBy('counts' , 'desc')
                ->whereIn('entities_id', Auth::user()->getEntityRoleEntityIDs())
                ->get();
    print_r($items);

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

No comments:

Post a Comment

Please post any queries and comments here.