如果使用save(),则Laravel使列不存在

时间:2015-07-31 08:57:13

标签: php laravel laravel-5 eloquent

我不知道是否可能,但基本上我想要的是当我保存()一个对象并且找不到一列时,它应该自动添加到表中。

例如:

$information = new App\Information;
$meta = new App\Meta;

//Insert real info for $information
$information->save();

$meta->description = "random description" //This is an existing column
$meta->newColumn = "Random string" //This column doesn't exist

$information->meta()->save($meta);

所以我想要的是在Meta表中创建“newColumn”列,因为它不存在。

有没有办法在不创建新迁移的情况下执行此操作?

编辑: 我发现了一种方法,我认为这是最好的方法,我猜...

if (!Schema::hasColumn('meta', 'newColumn')){
  Schema::Table('meta',function($table){
    $table->string('newColumn');
  });
}

如果有人有更好的解决方案。随意添加

最终编辑:

感谢大家的意见和帮助,但我们设计了一个新的数据库表,允许我们根据需要动态添加新数据。仍然感谢您的所有努力:)

1 个答案:

答案 0 :(得分:2)

我认为动态表设计是一个坏主意。为什么不创建一个新表格,例如Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{ // your code });

fields

其中ID是增量编号,Pid是您实际使用的ID | Pid | FieldName | Content 表中保存的记录的ID。

实施例

meta表:

Meta

ID | Description | StaticField1 | StaticField2 ---------------------------------------------- 1 | aaa | a1 | a2 2 | bbb | b1 | b2 3 | ccc | c1 | c2 4 | ddd | d1 | d2 表:

Fields

ID | Pid | FieldName | Content ------------------------------ 1 | 1 | field 1 | content 1 2 | 1 | field 2 | content 2 3 | 1 | field 3 | content 3 4 | 2 | field 1 | content 4 5 | 2 | field 2 | content 5 Fields.Pid有关,因此这意味着: 元Meta.ID还有3个名为aaafield 1field 2的字段。元field 3只有2个字段bbbfield 1。 因此,您现在只需在field 2表中创建一条新记录,而不是将字段的新列添加到Meta表中。