2016-05-21 18 views
13

Tôi muốn thêm cột trong bảng hiện tại của tôi trong CakePHP 3.động thêm các cột trong một bảng hiện có trên bay trong CakePHP 3

tôi đang ContactsTable.php file:

<?php 
namespace App\Model\Table; 
use Cake\ORM\Table; 
use Migrations\AbstractMigration; 

class ContactsTable extends Table 
{ 
    public function initialize(array $config) 
    { 
     $this->addBehavior('Timestamp'); 
     $table = $this->table('contacts'); 
     $table->addColumn('price', 'decimal')->update(); 

    } 
} 

Tôi đã thử như mô tả trong tài liệu CakePHP 3 nhưng tôi gặp lỗi này:

Call to a member function addColumn() on a non-object

Làm cách nào để thêm các cột trong khi di chuyển qua bộ điều khiển?

+0

bạn đã thử '$ table-> schema() -> addColumn ('price', 'decimal') -> update();'? Chỉ cần một đoán, không biết nhiều về di cư trong cakephp – arilia

+0

@arilia Bạn có thể tham khảo với một liên kết tài liệu? Tôi nghĩ bạn gần gũi. – Karma

Trả lời

6

Code:

<?php 

namespace App\Controller; 

use Cake\Core\Configure; 
use Cake\Network\Exception\NotFoundException; 
use Cake\View\Exception\MissingTemplateException; 
use Cake\ORM\TableRegistry; 
use Cake\Database\Schema\Table; 
use Cake\Datasource\ConnectionManager; 
use \Migrations\AbstractMigration as AbstractMigration; 
use \Phinx\Db\Adapter\MysqlAdapter as MysqlAdapter; 

class PagesController extends AppController 
{ 
    public function display() 
    { 
     $connectionArray = ConnectionManager::get('default')->config(); 
     $connectionArray['pass'] = $connectionArray['password']; 
     $connectionArray['user'] = $connectionArray['username']; 
     $connectionArray['name'] = $connectionArray['database']; 

     $migrationObject = new AbstractMigration(mt_rand()); 
     $migrationObject->setAdapter(new MysqlAdapter($connectionArray)); 
     $tree = $migrationObject->table('tests'); 


     $tree->addColumn('something', 'text') 
         ->update(); 
    } 
} 

Sau vài giờ Hacking, cuối cùng tìm thấy một cách để làm điều đó on-the-fly.

Tested trong mặc định CakePHP 3 (mới nhất - đến ngày hôm nay - ngày 02 Tháng 6 '16)

Nếu bạn đang sử dụng một bộ chuyển đổi cơ sở dữ liệu khác nhau, thay đổi nó để mà adapater từ MysqlAdapter.

Note to the users:

  • This is an ugly hack and should be used ONLY if you do not work in an organization where each migration commit requires peer reference.

  • mt_rand() must NEVER be used as a version number hack.

  • There is no canonical way of doing it via the controllers. Update in a datasource MUST always be done modified via migrations - using a proper structure.

  • Refer to Running Migrations in a non-shell environment and try to create a migrations logs under /config/migrations , that would be more rule-specific-on-the-fly and you will also have logs for peers to review.

1

Nếu bạn muốn thêm cột mới vào bảng sản phẩm ví dụ 'giá' và giá cả là một 'thập phân' bạn nên đến dự án của bạn và viết những dòng này trong giao diện điều khiển:

bin/cake bake migration AddPriceToProducts price:decimal 

Bạn có thể thấy một tập tin mới ví dụ Config/Migrations/20160501190410_AddPriceToProducts.php

<?php 
use Migrations\AbstractMigration; 

class AddPriceToProducts extends AbstractMigration 
{ 
    /** 
    * Change Method. 
    * 
    * More information on this method is available here: 
    * http://docs.phinx.org/en/latest/migrations.html#the-change-method 
    * @return void 
    */ 
    public function change() 
    { 
     $table = $this->table('products'); 
     $table->addColumn('price', 'decimal', [ 
      'default' => null, 
      ... 
      'null' => true, 
     ]); 
     $table->update(); 
    } 
} 

và sau đó chỉ cần khởi động di cư để thêm cột này để cơ sở dữ liệu, hãy viết này trong giao diện điều khiển:

bin/cake migrations migrate 
+1

Cảm ơn Jacek B Budzyñski. Trong hệ thống của tôi, người dùng có thể tự động tạo cột theo ý muốn của người dùng. Vì vậy, khi người dùng muốn thêm nhiều hơn một cột, anh ta không thể làm mã điều khiển này. Có bất kỳ mã nào bắt đầu di chuyển và sau đó thêm cột mà không có công cụ điều khiển đó? –

+1

@JigarDhaduk bạn có thể thêm nhiều cột 'bin/bánh nướng di chuyển AddPriceAndDiscountAndSomeToProducts price: decimal discount: số nguyên một số: string' nhưng tôi không biết làm thế nào để làm điều đó mà không cần giao diện điều khiển .. xin lỗi –

+0

Sửa câu hỏi. @ JacekBBudzyñski, OP muốn hỏi về làm thế nào để làm điều đó on-the-fly. – Karma

1

Migration plugin cũng hỗ trợ Running Migrations in a non-shell environment.

Since the release of version 1.2 of the migrations plugin, you can run migrations from a non-shell environment, directly from an app, by using the new Migrations class. This can be handy in case you are developing a plugin installer for a CMS for instance. The Migrations class allows you to run the following commands from the migrations shell: migrate , rollback , markMigrated , status and seed .

Each of these commands has a method defined in the Migrations class.

Bạn có thể chuẩn bị một số trình xử lý tùy chỉnh sẽ chấp nhận dữ liệu cột từ phía người dùng và chạy di chuyển. Trong trường hợp này, nó có thể là một số biểu mẫu với các đầu vào nametype. Di chuyển sẽ được áp dụng cho DB sau khi biểu mẫu có dữ liệu sẽ được gửi.

Dưới đây là làm thế nào để sử dụng nó:

use Migrations\Migrations; 

$migrations = new Migrations(); 

// Will return an array of all migrations and their status 
$status = $migrations->status(); 

// Will return true if success. If an error occurred, an exception will be thrown 
$migrate = $migrations->migrate(); 

// Will return true if success. If an error occurred, an exception will be thrown 
$rollback = $migrations->rollback(); 

// Will return true if success. If an error occurred, an exception will be thrown 
$markMigrated = $migrations->markMigrated(20150804222900); 

// Will return true if success. If an error occurred, an exception will be thrown 
$seeded = $migrations->seed(); 
+0

$ tsg Cảm ơn bạn đã trả lời. Nhưng làm thế nào tôi có thể thêm cột mới bằng mã này? Bạn vui lòng đưa ra ví dụ nào không? –

+1

Đây chỉ đơn giản là một bản sao dán nội dung – Karma

Các vấn đề liên quan