php - Laravel Seed 更新另一个表上的列

标签 php database laravel-5 laravel-seeding

我正在使用两个表。

例如,我将使用帖子。

第一个是帖子表

id|name |author|author_id|country
1 |test |Devin |1        |South Africa
2 |test2|James |2        |Whales
3 |test3|Devin |1        |South Africa

然后我有作者表

id|name
1 |Devin
2 |James

我想将国家/地区添加到作者表中。所以我进行了迁移以使我的表格看起来像这样

id|name  |country
1 |Devin |NULL
2 |James |NULL

现在我想要实现的是编写一个数据库播种器,它将根据帖子表将国家/地区播种到作者表中。

我想获取该author_id的帖子国家/地区,然后将该国家/地区插入到作者表中,使其看起来像这样

id|name  |country
1 |Devin |South Africa
2 |James |Whales

我的问题是,是否可以使用播种机来做到这一点?或者是否有更好的方法来做到这一点,而不必为每个作者手动执行此操作。

我想做这样的事情

<?php

use Illuminate\Database\Seeder;

class AlterOperatorsData extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $authors = App\Author::all();

        foreach ($authors as $author) {
            $country = App\Post::where('author_id', $author->id)->get()->first();
            DB::table('authors')->update([
                'country' => $country->country
            ]);
        }
    }
}

但这看起来会做一些繁重的工作,任何人都可以建议更好的方法,甚至看看当前的方法是否可以改进?

最佳答案

在这种情况下,正如OP在评论中所解释的那样,我只能建议对其功能进行一些小的优化。您不需要同时使用 get()first(),只有 first() 才能完成这项工作:

而不是

$country = App\Post::where('author_id', $author->id)->get()->first();

使用

$country = App\Post::where('author_id', $author->id)->first();

关于php - Laravel Seed 更新另一个表上的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042289/

相关文章:

mysql - 如何查找表中相对于初始 SQL fixture 的更改?

mysql - 统计数据库中某个字段的个数

php - 在 laravel 中检查这个吗?

php - 来自 PHP 结果的 jQuery json

PhpStorm 不识别类别名

database - 在不覆盖数据库用户的情况下恢复 SQL Server 2005 数据库

mysql - 优化这段 MYSQL 代码以获得更好的执行时间

php - 如何处理laravel登录错误,用户名与密码不同

php - Laravel 在查询 JSONB 列(转换为数组)时是否调用 json_decode 一次或多次?

php - Laravel 中的嵌套评论系统