gpt4 book ai didi

laravel - 数据库 :seed and passing variables for one to many relationship laravel

转载 作者:行者123 更新时间:2023-12-02 01:51:36 27 4
gpt4 key购买 nike

我正在尝试为数据库做种,我有两个问题

1)当存在一对多关系时,我想在新的种子类中传递另一个类(以前的表)的参数。我怎样才能做到这一点?

2)$row1->table2()->attach($row2->id); 我用它实现的是将 table2 的所有 id 附加到表 1,对吧?

编辑:

class LanguageTableSeeder extends Seeder {

public function run() {

$lingua_it_catFintapelle= Linguacat::create(array(
'nome' => 'Finta pelle',
'descrizione' => 'Finta pelle nautica/Finta pelle tempo libero/Finta pelle aviazione/Finta pelle automoto/finta pelle contract/finta pelle uffici/finta pelle esterni',
'lingua' => 'it-IT',
'id_cat' => $catFintaPelle->id
));

我有这段代码,问题是 id_cat 字段来 self 已经播种的另一个类的另一个表,在数据库播种器类中播种所有允许我重用这样的变量:

class DatabaseSeeder extends Seeder {

/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Eloquent::unguard();


$this->call('Seeder');
$this->command->info('Seed complete.');
}

}


class CatTableSeeder extends Seeder {

public function run() {

$catFintaPelle = Cat::create(array(
'path_img' => '/img/Materiale Imbottitura'

));
}
}

class LanguageTableSeeder extends Seeder {

public function run() {

$lingua_it_catFintapelle= Linguacat::create(array(
'nome' => 'Finta pelle',
'descrizione' => 'Finta pelle nautica/Finta pelle tempo libero/Finta pelle aviazione/Finta pelle automoto/finta pelle contract/finta pelle uffici/finta pelle esterni',
'lingua' => 'it-IT',
'id_cat' => $catFintaPelle->id
));
}
}

你看这里,我可以在新的种子中重用种子的 id 变量,节省我的时间。但我在某处读到,每张 table 的每个种子都应该有自己的类(class)。

最佳答案

当您播种时,假设您播种到一个新的数据库,因此您可以只对值进行硬编码而不是从另一个表加载它们。

如果你想附上所有的 id,你可以这样做:

$ids = OtherTable::all()->lists('id'); // this will generate an array of ids

$row1->table2()->sync($ids); // sync the ids with the relation

关于laravel - 数据库 :seed and passing variables for one to many relationship laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22365580/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com