0

所以我试图从外部 api 而不是使用 Laravel 中的模型工厂的默认伪造者将数据播种到我的 dB 中,但我被卡住了。下面是我的代码:

$factory->define(\App\Models\State::class, function(){
    $client = new Client();
    $stateQuery = $client->get('http://states-and-cities.com/api/v1/states');
    $states = $stateQuery->getBody();
    $states = json_decode($states, true);
    foreach ($states as $state) {
        return [
            'name' => $state['name'],
        ];
    }
});

所以发生的事情是,预期的回报是只播种一个记录,但我需要它来播种整个记录。我怎样才能解决这个问题?

4

1 回答 1

0

您可以尝试如下:

$client = new Client();
$stateQuery = $client->get('http://states-and-cities.com/api/v1/states');
$states = $stateQuery->getBody();
$states = json_decode($states, true);
foreach ($states as $state) {
    \App\Models\State::create(['name' => $state['name']]);
}
于 2016-11-10T13:55:24.747 回答