saadaan's avatar

Creating MySQL views in migration, and making a model from it

Hi,

I need to pick up data from a database different from the laravel project one. Can I make an 'SQL view' in laravel database, which is a collection of relevant fields from different tables from other databases? How to make its migration? And can I make a model on top of this migration as well?

Thanks, Saad

0 likes
3 replies
whitenazgul's avatar

I use views all the time for reporting purposes as I can create a denormalized view and then use the power of Models with Scopes and mutators.

Here is how I create a view.

Create a new migration

php artisan make:migration create_employees_record_view

Update the migration

<?php

use Illuminate\Database\Migrations\Migration;

class CreateEmployeesRecordView extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        \DB::statement("
            CREATE VIEW employees_records 
            AS
            SELECT
                employees.emp_no,
                employees.first_name,
                employees.last_name,
                employees.gender,
                employees.hire_date,
                employees.birth_date,
                dept_emp.dept_no,
                departments.dept_name,
                mananger.emp_no AS manager_emp_no,
                mananger.first_name AS manager_first_name,
                mananger.last_name AS manager_last_name
            FROM
                employees
                LEFT JOIN dept_emp ON employees.emp_no = dept_emp.emp_no
                LEFT JOIN departments ON dept_emp.dept_no = departments.dept_no
                LEFT JOIN dept_manager ON departments.dept_no = dept_manager.dept_no
                LEFT JOIN employees mananger ON dept_manager.emp_no = mananger.emp_no;
        ");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
    }
}


# Run the migration
php artisan migrate

Effectively Manage View

http://blog.tekz.io/laravel-eloquent-how-to-effectively-manage-sql-views/

2 likes

Please or to participate in this conversation.