Laravel 种子从另一个表上的列更新列



我有两个正在使用的表。

例如,我将使用帖子。

第一个是帖子表

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 IlluminateDatabaseSeeder;
class AlterOperatorsData extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $authors = AppAuthor::all();
        foreach ($authors as $author) {
            $country = AppPost::where('author_id', $author->id)->get()->first();
            DB::table('authors')->update([
                'country' => $country->country
            ]);
        }
    }
}

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

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

而不是

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

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

最新更新