Laravel将数据数组插入数据库

时间:2022-09-26 08:17:25

I have this line of codes at my Controller to get data from google analytics

我在我的控制器上有这行代码来从谷歌分析中获取数据

$analyticsData = Analytics::performQuery(Period::days(30),
    'ga:',
    [
        'metrics' => 'ga:users,ga:newUsers,ga:sessions,ga:sessionsPerUser,ga:pageviews,ga:pageviewsPerSession,ga:avgSessionDuration,ga:bounceRate',
        'start-date' => '2018-08-01',
        'end-date' => '2018-09-02',
        'dimensions' => 'ga:pageTitle',
    ]);

When I dd($analyticsData); This is what I got.

当我dd($ analyticsData);这就是我得到的。

Laravel将数据数组插入数据库

This is my migration query.

这是我的迁移查询。

    Schema::create('analytics', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('site_id');
        $table->string('site_url');
        $table->integer('report_id');
        $table->integer('analytics_view_id'); 
        $table->date('reportGenerated');
        $table->integer('gaUsers');
        $table->integer('gaNewUsers');
        $table->integer('gaSessions');
        $table->integer('gaSessionsPerUser');
        $table->integer('gaPageviews');
        $table->integer('gaPageviewsPerSession');
        $table->integer('gaAvgSession');
        $table->integer('gaBounceRate');

    });

Now my problem is how can I able to stores those array data to my database? Thank you.

现在我的问题是如何才能将这些数组数据存储到我的数据库中?谢谢。

2 个解决方案

#1


1  

It would be something like:

它会是这样的:

$model = Analytics::create([
   'gaUsers' => $analyticsData['ga:users'],
   'gaNewUsers' => $analyticsData['ga:newUsers'],
   // ... and so on...
]);

Just in case make sure you have those fields in $fillable attribute of your Analytics model.

以防万一您确保在Analytics模型的$ fillable属性中包含这些字段。

#2


1  

Try:

$analytic = new Analytics();

$analytic->gaUsers = $analyticsData['ga:users'];
$analytic->gaNewUsers = $analyticsData['ga:newUsers'];
...
$analytic->save();

#1


1  

It would be something like:

它会是这样的:

$model = Analytics::create([
   'gaUsers' => $analyticsData['ga:users'],
   'gaNewUsers' => $analyticsData['ga:newUsers'],
   // ... and so on...
]);

Just in case make sure you have those fields in $fillable attribute of your Analytics model.

以防万一您确保在Analytics模型的$ fillable属性中包含这些字段。

#2


1  

Try:

$analytic = new Analytics();

$analytic->gaUsers = $analyticsData['ga:users'];
$analytic->gaNewUsers = $analyticsData['ga:newUsers'];
...
$analytic->save();