我有一个名为的.txt
文件
john doe
mary roe
...
...
我有一个型号Person
,它有以下$fillable
:
protected $fillable = [
'list_id',
'name'
];
我正试图用这个特定文件中的名称填充一个特定的List
,但我有点难以理解如何正确地执行此操作。我主要想在数据库中添加一系列列表和每个列表上的名称(每个列表来自.txt
文件(。
什么是阅读文件并告诉Laravel";嘿,把每一行都放在(比方说(清单1下面"?
$file = new SplFileObject(‘/path/to/your/file.txt’);
$list = List::where(…)->first(); // find the list matching your file
while (!$file->eof()) {
// assuming you have List::people() hasMany relation:
$list->people()->create([
’name’ => trim($file->fgets()); // you can format, trim, sanitize your line here
]);
// Without relation:
Person::create([
’list_id’ => $list->id,
‘name’ => trim($file->fgets());
]);
}
解决方案是:
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
// Echo one line from the file.
$echo $file->fgets();
}
$file = null;
希望这能帮助到其他人。
Hi-SplFileObject是一种简洁的方法,面向对象,进一步信息:SplFileObject
$myFile = new SplFileObject("data.txt");
while (!$myFile->eof()) {
echo $myFile->fgets() . PHP_EOL; //line N
//Here you can pass list id and the value retrieved above and store it on the DB
}