1

我有两个正在使用的表。

例如,我将使用帖子。

第一个是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
            ]);
        }
    }
}

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

4

1 回答 1

1

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

代替

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

利用

$country = App\Post::where('author_id', $author->id)->first();
于 2017-03-27T09:28:34.463 回答