我有两个正在使用的表。
例如,我将使用帖子。
第一个是posts表
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
我想将国家添加到 Authors 表中。所以我做了一个迁移,让我的桌子看起来像这样
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
]);
}
}
}
但这看起来会做一些繁重的工作,任何人都可以提出更好的方法,或者甚至看看当前的方法,看看是否可以改进?