3 use Illuminate\Support\Facades\Schema;
4 use Illuminate\Database\Schema\Blueprint;
5 use Illuminate\Database\Migrations\Migration;
7 class CreateBookshelvesTable extends Migration
16 Schema::create('bookshelves', function (Blueprint $table) {
17 $table->increments('id');
18 $table->string('name', 200);
19 $table->string('slug', 200);
20 $table->text('description');
21 $table->integer('created_by')->nullable()->default(null);
22 $table->integer('updated_by')->nullable()->default(null);
23 $table->boolean('restricted')->default(false);
24 $table->integer('image_id')->nullable()->default(null);
27 $table->index('slug');
28 $table->index('created_by');
29 $table->index('updated_by');
30 $table->index('restricted');
33 Schema::create('bookshelves_books', function (Blueprint $table) {
34 $table->integer('bookshelf_id')->unsigned();
35 $table->integer('book_id')->unsigned();
37 $table->foreign('bookshelf_id')->references('id')->on('bookshelves')
38 ->onUpdate('cascade')->onDelete('cascade');
39 $table->foreign('book_id')->references('id')->on('books')
40 ->onUpdate('cascade')->onDelete('cascade');
42 $table->primary(['bookshelf_id', 'book_id']);
45 // Copy existing role permissions from Books
46 $ops = ['View All', 'View Own', 'Create All', 'Create Own', 'Update All', 'Update Own', 'Delete All', 'Delete Own'];
47 foreach ($ops as $op) {
48 $dbOpName = strtolower(str_replace(' ', '-', $op));
49 $roleIdsWithBookPermission = DB::table('role_permissions')
50 ->leftJoin('permission_role', 'role_permissions.id', '=', 'permission_role.permission_id')
51 ->leftJoin('roles', 'roles.id', '=', 'permission_role.role_id')
52 ->where('role_permissions.name', '=', 'book-' . $dbOpName)->get(['roles.id'])->pluck('id');
54 $permId = DB::table('role_permissions')->insertGetId([
55 'name' => 'bookshelf-' . $dbOpName,
56 'display_name' => $op . ' ' . 'BookShelves',
57 'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
58 'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
61 $rowsToInsert = $roleIdsWithBookPermission->map(function($roleId) use ($permId) {
64 'permission_id' => $permId
68 // Assign view permission to all current roles
69 DB::table('permission_role')->insert($rowsToInsert);
74 * Reverse the migrations.
78 public function down()
80 // Drop created permissions
81 $ops = ['bookshelf-create-all','bookshelf-create-own','bookshelf-delete-all','bookshelf-delete-own','bookshelf-update-all','bookshelf-update-own','bookshelf-view-all','bookshelf-view-own'];
83 $permissionIds = DB::table('role_permissions')->whereIn('name', $ops)
84 ->get(['id'])->pluck('id')->toArray();
85 DB::table('permission_role')->whereIn('permission_id', $permissionIds)->delete();
86 DB::table('role_permissions')->whereIn('id', $permissionIds)->delete();
89 Schema::dropIfExists('bookshelves');
90 Schema::dropIfExists('bookshelves_books');