如何在Laravel中使用php artisan创建数据库视图的迁移?

时间:2016-03-29 14:33:46

标签: php laravel laravel-5.2

实际上,我已经设法使用PHP Artisan使用以下步骤为Laravel创建了一个sql视图。

步骤1.运行以下命令:

php artisan make:migration create_overall_report_views

第2步。

打开迁移文件并添加以下代码:

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');
  }  

}

步骤3.通过Laravel查询调用和运行SQL视图

$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);

希望有所帮助。如果有人有更好的解决方案,请告诉我!

6 个答案:

答案 0 :(得分:18)

偶然发现了同样的问题并找到了解决方案@ 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");
    }
}

答案 1 :(得分:1)

使用up功能中的“创建或替换”这样编写迁移:

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');
    }

答案 2 :(得分:0)

您也可以尝试使用此DB :: connection()-> getPdo()-> exec(“您的sql查询”);它有效

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 ...");
        }
    }

答案 3 :(得分:0)

我已经创建了一个用于创建,重命名和删除视图的包:
https://github.com/staudenmeir/laravel-migration-views

您可以提供查询生成器实例或SQL字符串:

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');
    }  
}

答案 4 :(得分:0)

您可以这样做:

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;
}

现在我们已经进行了迁移,所有其他功能都像正常的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);
   }
}

引用:https://stitcher.io/blog/eloquent-mysql-views

答案 5 :(得分:-14)

你必须使用laravel eloquent创建模型之间的关系。 例如: 如果您有2个表(角色,用户),并且它们之间的关系是多对多,您必须创建模型角色和用户,然后在角色模型中编写以下代码:     公共功能用户()     {     return $ this-&gt; belongsaToMany('App / User');     }

并在用户模型中:

public function roles()
{
return $this->belongsToMany('App/Role')
}

之后创建一个新的迁移并将表名称为role_user并将下面的代码放入:

public function up()
{
Schema::create('category_post', function (Blueprint      $table){
$table->increments('id')->unsigned();
$table->integer('post_id')->unsigned()->index();
$table->integer('category_id')->unsigned()->index();
$table->timestamps();
$table->foreign('category_id')
->references('id')->on('categories')
->onUpdate('cascade')
->onDelete('cascade');$table->foreign('post_id')
->references('id')->on('posts')
->onUpdate('cascade')
->onDelete('cascade');
});
}

保存并运行php artisan migrate。 它完成了,现在你有很多关系。 在完成所有这些以便为用户提供相关角色的查询示例之后,将您的用户和角色模型添加到您的控制器中,执行以下操作:

    public function edit($id){
    $user=User::whereId($id)->firstOrFail();
    $roles=Role::all()
    $selectedRole=$user->roles()->lists('id')->toArray();
    return view('your page          view',compact($user,$roles,$selectedRole));
    }

并在视图中显示所选角色:

<select id="role" name="role[]" multiple>
@foreach($roles as $role)
<option value="{!! $role->id !!}" @if(in_array($role->id,    $selectedRoles)) selected="selected" @endif >
{!! $role->display_name !!}
</option>
@endforeach
</select>

结束了。