如何使用laravel

时间:2018-04-16 22:11:04

标签: php arrays laravel

我正在努力解决如何将此数组插入数据库的问题。我有一个2D数组作为PUT请求发送(我认为它实际上是一个对象$ request)。该阵列包含有关个人培训计划的信息。数组中的第一个维度指定星期几。第二个指定哪些值属于哪个类别/列以及哪一天。在我目前的例子中,我只提交星期一的运动计划,再次由数组中的第一级表示,因为1星期二将是2,依此类推。我正确填充了exercise_plans表,因为它不是2D。这是我无法弄清楚的exercise_plan_details表。

$ request-> reps [1] [0]将是周一第一次演习的代表数量。

$ request-> reps [1] [1]将是周一第二次演习的第二位代表数量

$ request-> reps [2] [0]将是星期二第一次演习的代表数量。

$ request-> reps [2] [1]将是周二第二次演习的第二位代表数量

星期一可能没有任何练习,而星期五可能有8个。

我希望你理解,任何帮助将不胜感激。

这是使用$ request-> all()

打印的数组
 array(8) {
  ["_token"]=>
  string(40) "DAOV7rwCjZhnC8cZMmYRsPRLEjnMIZi8CERAwibD"
  ["title"]=>
  string(4) "test"
  ["queue"]=>
  string(12) "Add Exercise"
  ["exerciseList"]=>
  array(1) {
    [1]=>
    array(3) {
      [0]=>
      string(1) "3"
      [1]=>
      string(1) "3"
      [2]=>
      string(1) "4"
    }
  }
  ["reps"]=>
  array(1) {
    [1]=>
    array(3) {
      [0]=>
      string(2) "11"
      [1]=>
      string(2) "44"
      [2]=>
      string(2) "77"
    }
  }
  ["sets"]=>
  array(1) {
    [1]=>
    array(3) {
      [0]=>
      string(2) "22"
      [1]=>
      string(2) "55"
      [2]=>
      string(2) "88"
    }
  }
  ["weight"]=>
  array(1) {
    [1]=>
    array(3) {
      [0]=>
      string(2) "33"
      [1]=>
      string(2) "66"
      [2]=>
      string(2) "99"
    }
  }
  ["_method"]=>
  string(3) "PUT"
}

作为请求对象发送的数组的另一个视图

enter image description here

数据库:

enter image description here

以下是我手动插入一行的方法

$array = $request->all();

var_dump($array);

$post = new ExercisePlan();
$post->trainerID = Auth::user()->id;
$post->name = $request->input('title');
$post->save();

$details = new ExercisePlanDetails();
$details->planID = $post->id;
$details->day = "Monday";
$details->exerciseID = $request->exerciseList[1][0];
$details->reps = $request->reps[1][0];
$details->sets = $request->sets[1][0];
$details->priority = "1";
$details->weight = $request->weight[1][0];
$details->save();

这种手动方式仅用于测试,但我认为我需要一个双重来获取所有数据到数据库?有任何想法吗?

1 个答案:

答案 0 :(得分:0)

首先,我要做的是使用ExercisePlan方法在ExercisePlanDetailsdetails之间建立关系,并添加$fillable属性,以便能够使用create进行质量赋值{1}}稍后发表声明。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ExercisePlan extends Model
{
    protected $fillable = [
        'trainerID',
        'name'
    ];

    public function details(): HasMany
    {
        return $this->hasMany(ExercisePlanDetails::class, 'planID', 'id');
    }
}

确保您的ExercisePlanDetail模型还具有$fillable属性集

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ExercisePlanDetails extends Model
{
    protected $fillable = [
        'day',
        'exerciseID',
        'reps',
        'sets',
        'priority',
        'weight'
    ];
}

现在从控制器内部,为了为给定的计划创建多个ExercisePlanDetails记录,我们可以首先为每个详细记录生成一个数据数组,并在关系上使用createMany方法来添加它们所有人只需一次电话

<?php

namespace App\Http\Controllers;

use App\ExercisePlan;
use App\Utilities\Date;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;

class ExerciseController extends Controller
{
    public function store(Request $request): JsonResponse
    {
        $plan = ExercisePlan::create([
            'trainerID' => $request->user()->id,
            'name' => $request->input('title')
        ]);

        $details = collect($request->exerciseList)
            ->flatMap(function(array $exercises, int $dayId) use ($request) {
                return $this->parseEntry(
                    new Collection($exercises), $dayId, $request
                );
            })->toArray();

        $plan->details()->createMany($details);

        return new JsonResponse([], Response::HTTP_CREATED);
    }

    protected function parseEntry(Collection $exercises, int $dayId, Request $request): array
    {
        return $exercises->map(function(int $value, int $index) use ($dayId, $request) {
            return [
                'day' => Date::day($dayId),
                'exerciseID' => $value,
                'reps' => $request->reps[$dayId][$index],
                'sets' => $request->sets[$dayId][$index],
                'priority' => 1,
                'weight' => $request->weight[$dayId][$index],
            ];
        })->toArray();
    }

}

要获得day作为字符串,我使用静态方法day

创建了一个简单的实用工具类
<?php

namespace App\Utilities;

class Date
{
    public static function day(int $dayId): string
    {
        switch($dayId) {
            case 1:
                return 'Monday';
            case 2:
                return 'Tuesday';
            case 3:
                return 'Wednesday';
            case 4:
                return 'Thursday';
            case 5:
                return 'Friday';
            case 6:
                return 'Saturday';
            case 7:
                return 'Sunday';
            default:
                throw new \Exception('Invalid day');
        }
    }
}

我设置了以下路线

Route::put('/exercise', 'ExerciseController@store')->name('exercise.store');

以下测试,通过

<?php

namespace Tests\Feature;

use App\User;
use Tests\TestCase;
use App\ExercisePlan;

use Illuminate\Http\Response;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExerciseTest extends TestCase
{
    use RefreshDatabase;

    /**
     * @var \App\User
     */
    protected $user;

    public function setUp()
    {
        parent::setUp();

        $this->user = factory(User::class)->create();

        $this->actingAs($this->user);
    }

    /**
     * @test
     */
    public function adds_exercise_plan_with_plan_details()
    {
        $response = $this->put(route('exercise.store'), [
            'title' => 'Fake title',
            'queue' => 'Add Exercise',
            'exerciseList' => [
                1 => [3, 3, 4],
                5 => [4, 5, 6],
            ],
            'reps' => [
                1 => [11, 44, 77],
                5 => [12, 45, 78],
            ],
            'sets' => [
                1 => [22, 55, 88],
                5 => [23, 56, 89],
            ],
            'weight' => [
                1 => [33, 66, 99],
                5 => [34, 67, 100],
            ]
        ]);


        $response->assertStatus(Response::HTTP_CREATED);

        $plan = ExercisePlan::first();

        $this->assertEquals('Fake title', $plan->name);
        $this->assertEquals($this->user->id, $plan->trainerID);

        $this->assertCount(6, $plan->details);


        $this->assertEquals(
            [
                'day' => 'Monday',
                'exerciseID' => 3,
                'reps' => 11,
                'sets' => 22,
                'priority' => 1,
                'weight' => 33
            ],
            $plan->details->get(0)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

        $this->assertEquals(
            [
                'day' => 'Monday',
                'exerciseID' => 3,
                'reps' => 44,
                'sets' => 55,
                'priority' => 1,
                'weight' => 66
            ],
            $plan->details->get(1)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

        $this->assertEquals(
            [
                'day' => 'Monday',
                'exerciseID' => 4,
                'reps' => 77,
                'sets' => 88,
                'priority' => 1,
                'weight' => 99
            ],
            $plan->details->get(2)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

        $this->assertEquals(
            [
                'day' => 'Friday',
                'exerciseID' => 4,
                'reps' => 12,
                'sets' => 23,
                'priority' => 1,
                'weight' => 34
            ],
            $plan->details->get(3)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

        $this->assertEquals(
            [
                'day' => 'Friday',
                'exerciseID' => 5,
                'reps' => 45,
                'sets' => 56,
                'priority' => 1,
                'weight' => 67
            ],
            $plan->details->get(4)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

        $this->assertEquals(
            [
                'day' => 'Friday',
                'exerciseID' => 6,
                'reps' => 78,
                'sets' => 89,
                'priority' => 1,
                'weight' => 100
            ],
            $plan->details->get(5)->only(['day', 'exerciseID', 'reps', 'sets', 'priority', 'weight'])
        );

    }
}

希望这就是你要找的东西。