我用的是两张桌子。
例如,我将使用帖子。
第一个是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我想在作者表中添加一些国家。所以我做了一个迁移,让我的桌子看起来像这样
id|name |country
1 |Devin |NULL
2 |James |NULL现在,我想要实现的是编写一个数据库播种机,将这些国家种子发送到基于posts表的作者表中。
我想获取该author_id的posts国家,然后将国家插入到author表中,使其看起来如下
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
]);
}
}
}但是,这看起来会做一些繁重的工作,谁能提出更好的方法,甚至看看目前的方法,看看是否可以改进?
发布于 2017-03-27 09:28:34
在这种情况下,正如OP在评论中所解释的,我只是建议对他的函数进行一个小的优化。您不需要同时使用get()和first(),只有first()才能完成以下工作:
而不是
$country = App\Post::where('author_id', $author->id)->get()->first();使用
$country = App\Post::where('author_id', $author->id)->first();https://stackoverflow.com/questions/43042289
复制相似问题