[英]Update column automatically based on value of another column (same table) in Laravel (7)
[英]Laravel Seed update a column from column on another table
我有兩張桌子,我正在使用。
例如,我將使用帖子。
第一個是帖子表
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表將各國種子放入authors表中。
我想獲取該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
]);
}
}
}
但看起來它會做一些繁重的工作,任何人都可以建議一個更好的方法,或者甚至看看當前的方法,看看它是否可以改進?
那么就像OP在評論中解釋的那樣,我可以建議他的功能進行小的優化。 你不需要同時使用get()
和first()
,只有first()
才能完成這項工作:
代替
$country = App\Post::where('author_id', $author->id)->get()->first();
采用
$country = App\Post::where('author_id', $author->id)->first();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.