I'm trying to create a migration that makes a new column and fills it with data from existing column.

我正在尝试创建一个迁移,创建一个新列并使用现有列中的数据填充它。

I want to turn the name column into a slug (using the helper function) and save that in a slug column.

我想将名称列转换为slug(使用辅助函数)并将其保存在slug列中。

I've tried this but no luck:

我试过这个但没有运气:

public function up()
{
    Schema::table('teams', function(Blueprint $table)
    {
        //
        $table->string('slug', 100);
    });

    $teams = DB::table('teams')->get();

    foreach ($teams as $team)
    {
        $team->slug = str_slug($team->name, "-");
        $team->save();
    }
}

Am i being an idiot? Can i make this work?

我是个白痴吗?我可以做这个工作吗?

Thanks

谢谢

2 个解决方案

#1


4

Assuming you have a Team model:

假设你有一个团队模型:

$teams = App\Team::all();

foreach($teams as $team) {
    $team->slug =  str_slug($team->name, "-");
    $team->save();
}

You're trying to use Eloquent ORM syntax ($team->save) in a code that is actually using Query Builder. You'd better choose one or the other (ORM or Query building). My version uses Eloquent ORM. Of course you could have used Query Builder syntax all the way, like this:

您正尝试在实际使用查询生成器的代码中使用Eloquent ORM语法($ team-> save)。您最好选择其中一个(ORM或Query构建)。我的版本使用了Eloquent ORM。当然,您可以一直使用Query Builder语法,如下所示:

$teams = DB::table('teams');
foreach($teams as $team) {
    DB::table('teams')
            ->where('id', $team->id)
            ->update(['slug' => str_slug($team->name)]);
}

And basically a Query Builder select command (like $teams = DB::table('teams');) will return an array of stdClass objects (which have not a "save" method) , whereas Eloquent ORM select will return a collection of objects of the specified model, which do have the "save" method.

基本上Query Builder select命令(如$ teams = DB :: table('teams');)将返回一个stdClass对象数组(没有“save”方法),而Eloquent ORM select将返回一个具有“save”方法的指定模型的对象。

更多相关文章

  1. 从模型到控制器并返回到模型的数据
  2. 装机建项目vs2017和mysql5.7下建项目用EF建实体模型的过程..
  3. PHP解析错误:语法错误,意外的T_VARIABLE
  4. 可以在SELECT语句中嵌入描述语法吗?
  5. mysql语法之case when then与列转行
  6. MySQL数据库语法-多表查询练习一
  7. Netbeans6.1+JSF/VJSF/+JPA+MYSQL=酷炫快速开发模型
  8. 语法错误:从[{id}]开始的表达式[{id}]第2列的令牌'{'无效键?
  9. Javascript语法中null与“”的误写导致长期困扰的问题终于解决了

随机推荐

  1. Python机器学习之旅|手把手带你探索IRIS数
  2. 近期文章汇总
  3. 我来啦!
  4. 动画:面试官问我 0.1 + 0.2 0.3 ? 为什么
  5. 深入理解跳表在Redis中的应用
  6. Python办公自动化|从Excel到Word
  7. Pyecharts制作地图的几种方法评析
  8. 一道Leetcode数据库题的三种解法|文末送书
  9. 你在的城市撒币了吗?Python爬取全国各城市
  10. LeetCode数据库篇|175组合两个表