I have two tables that I am using.
for example I am going to use posts.
The first is the posts table
id|name |author|author_id|country
1 |test |Devin |1 |South Africa
2 |test2|James |2 |Whales
3 |test3|Devin |1 |South Africa
Then I have the authors table
id|name
1 |Devin
2 |James
I want to add countries to the Authors table. So I made a migration to get my table to look like this
id|name |country
1 |Devin |NULL
2 |James |NULL
Now what I am trying to achieve is to write a database seeder that will seed the countries into the authors table based on the posts table.
I want to grab the posts country for that author_id and then insert the country into the author table so that it will look like this
id|name |country
1 |Devin |South Africa
2 |James |Whales
My question is, is it possible to do this using a seeder? Or is there a better way to do this without having to do it manually for every author.
I thought to do something like this
<?php
use Illuminate\Database\Seeder;
class AlterOperatorsData extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$authors = Author::all();
foreach ($authors as $author) {
$country = App\Post::where('author_id', $author->id);
DB::table('authors')->update([
'country' => $country->country
]);
}
}
}
But that looks like it would do some heavy lifting, can anyone suggest a better method, or even take a look at the current method to see if it can be improved?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire