可以在我的create方法中添加数组吗?

问题描述 投票:1回答:2

试图为我的Account模型创建一个新记录。

我的模型有以下结构:'title','information','image','combat','quest','price'我的模型上还有24个项目被认为是skills

我想让这24个项目成为可能,我可以在我的创建方法中循环,这样我就不必手动添加我的创建中的所有技能。

模型如下所示:

public function up()
{
    Schema::create('accounts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('price');
        $table->string('image_url');
        $table->integer('quest_points');
        $table->string('title');
        $table->string('information');
        $table->integer('attack');
        $table->integer('defence');
        $table->integer('strength');
        $table->integer('constitution');
        $table->integer('cooking');
        $table->integer('construction');
        $table->integer('farming');
        $table->integer('crafting');
        $table->integer('firemaking');
        $table->integer('fishing');
        $table->integer('fletching');
        $table->integer('herblore');
        $table->integer('hunter');
        $table->integer('magic');
        $table->integer('mining');
        $table->integer('prayer');
        $table->integer('ranged');
        $table->integer('runecrafting');
        $table->integer('slayer');
        $table->integer('smithing');
        $table->integer('agility');
        $table->integer('thieving');
        $table->integer('woodcutting');
        $table->integer('total_level');
        $table->integer('combat_level');
        $table->timestamps();
    });
}

我的创建方法:

public function store(Request $request)
{
    $account = $request->all('title','description','image','combat','quest','price');
    $skills = $request->get('skill');

    // array of 24 items, example -> 'attack' = 52;  

    Account::create([
        'title' => $account['title'],
        'price' => $account['price'],
        'information' => $account['description'],
        'image_url' => $account['image'],
        'combat_level' => $account['combat'],
        'quest_points' => $account['quest'],

        // I would do the following normally

        'attack' => $skills['attack'],
        'defence' => $skills['defence'],

        // ....
        // possible to do this with a loop of the array $skills? 

    ]);

}
php laravel eloquent
2个回答
4
投票

在输入字段中为表列提供相同的名称,然后可以使用以下内容创建记录。它应该工作

$mergedArray = array_merge($account, $skills);
Account::create($mergedArray);

3
投票

首先确保输入字段的名称与表记录的名称相同,然后您可以使用以下内容创建记录:

Account::create($skills);

如果你想在账户模型中插入许多技能,你可以使用insert方法

$skills = array(
    $array_of_skills,
    $array_of_skills_,
    //...
);

Account::insert($skills);
© www.soinside.com 2019 - 2024. All rights reserved.