Laravel dodawanie tabeli i pobieranie do niej danych

0

Witam bazując na pewnym projekcie potrzebuje wyciągnać z pewnych pilków które generują dane, dane do mojej tabeli. I wszystko chyba jest ok ale czegoś nie kumam albo coś jest żle.
Utworzyłem tabele która znajduje sie w mojej bazie danych generator_logs . W tabeli utworzyłem konto allegro [allegro_account]; ilość wygenerowanych zestawów/setów [item_quantity]; rodzaj (sets/variants) [type]; data wygenerowania łącznie z godziną [created_at]

Tabela się utworzyła wszystko ok. Tylko jak teraz mam przeslać do niej te dane ? komeda php artisan migrate? db:seed ? Proszę spójrzcie też na moje pliki czy to dobrze robie.
2020_09_10_105111_create_generator_logs_table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGeneratorLogsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('generator_logs', function (Blueprint $table) {
            $table->id();
            $table->string('allegro_account');
            $table->integer('item_quantity');
            $table->string('type');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('generator_logs');
    }
}


Tutaj jest mój model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Generator_log extends Model
{
    protected $fillable = ['allegro_account', 'item_quantity', 'type'];

}

I teraz repozytorium do mojej bazy danych z zapytaniami tutaj mam problem nie wiem czy to jest dobry zapis? Wiem ze laravel ma wiele wbudowanych narzedzi do operacji na bazach danych.

<?php
namespace App\Repositories;
use App\Models\Generator_log;

use App\Services\Allegro\Sets;
use App\Console\Commands\GenerateSets;
use App\Console\Commands\GenerateVariants;

// #Repository for Sets and Variants

class GeneratorLogsRepository {

    /**
     * @return mixed
     */
    public function getSets()
    {
        return Sets::get();
    }


    /**
     * @param $sets
     * @param $name
     * @param @type
     * @return mixed
     */
    public function inserts($sets, $name , $type){

        $this->model::create([
            'allegro_account' => $name["test1"],
            'item_quantity' => $sets["test2"],
            'type' => $type["type3"],
        ]);
    }

}

I tutaj chodzi o to że do bazy danych ma wpadać albo zestawy albo warianty. Oczywiście są one generowane przez inne 2 pliki. W kolumnie type ma mi przesyłac w zaleznosci od typu albo wariant(variants) albo zestaw(sets). Czy po wywaleniu tych testów w kwadratowych nawiasach przejdzie mi to do bazy?
Tutaj mój plik GenerateSets.php

<?php

namespace App\Console\Commands;

use App\Repositories\GeneratorLogsRepository;
use App\Services\Allegro\Sets;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class GenerateSets extends Command
{
    use AllegroAuthentically;

    protected $signature = 'set:generate {account?}';
    protected $description = 'Generate Product Set for allegro auctions';

    private $sets;
    const TYPE = "sets";

    public function __construct()
    {
        parent::__construct();
    }
    
    public function handle()
    {
        // Use AllegroAuthentically trait authorization
        $account = $this->authorization();

        // Crate service
        $sets = new Sets($account);

        // Get all variants
        $bundleSets = $sets->calculateSets();

        // Create sets
        foreach($bundleSets as $offers)
        {
            print_r($offers);
           // $sets->create($offers);
        }
        $glr = new GeneratorLogsRepository();

        $glr->updateOrCreate(count($bundleSets), $account['login'], static::TYPE);


    }
}

A tutaj plik od tych wariantów nie wazne czym to jest chodzi mi teraz o parametry czy dobrze wszystko podpinam i przejdą do mojego repozytorium od bazy.

<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Notifications\VariantGenerationCompleted;
use App\Services\Allegro as AllegroService;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Notification;

class GenerateVariants extends Command
{
    const TYPE = "variant";
    use AllegroAuthentically;

    protected $signature = 'variant:generate {account?}';
    protected $description = 'Generate product variants map';

    private $allegroConnector;
    private $allegroService;

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Use AllegroAuthentically trait authorization
        $account = $this->authorization();

        // Crate service
        $this->allegroService = new AllegroService($account);
$this->allegroService->generateNewVariants();

        // User security - are you sure to do it
        if(!$this->force) {
            if (!$this->confirm('Are you sure you want to create new variants?' . PHP_EOL))  {
                $this->line('Aborting');
                die();
            }
        }

        $this->line( 'Creating variant sets: ' . PHP_EOL);

        $variantsCount = 0;
        // Get variant to insert
        while($variant = $this->allegroService->getVariantToInsert())
        {
            try {

                // Create variant
                $this->allegroConnector->createVariant($variant['name'], $variant['auctions']);
                $variantsCount++;

                // Show variant
                debug($variant['name']);

                // Debug variant
                //if(env('APP_DEBUG'))
                //    Notification::send(User::first(), new VariantGenerationCompleted($variant, $this->account));
            }
            catch(ClientException $e) {
                debug(json_decode($e->getResponse()->getBody()->getContents(), 1));
            }
        }

        $glr = new GeneratorLogsRepository();

        $glr->updateOrCreate($variantsCount, $account['login'], static::TYPE);

        $this->line(PHP_EOL . 'Finished No more variants to go.');
    }

    private function handleCreateError($e, $variantName)
    {
        // Not active offer
        if(strpos($e->getMessage(), 'It is allowed to add only active offers to a variant set'))
            $this->removeUnactivatedOffers($e->getMessage(), $variantName);
    }

    /**
     * @param $message
     * @param $variantName
     */
    private function removeUnactivatedOffers($message, $variantName)
    {
        // Get offers id
        $offersId = $this->getOffersIdFromMessage($message);

        // Remove offers from variant
        foreach($offersId as $offer)
            $this->allegroConnector->removeAuctionFromVariant($offer, $variantName);
    }

    /**
     * @param $message
     * @return mixed
     */
    private function getOffersIdFromMessage($message)
    {
        preg_match_all('!\d+!', $message, $offersId);
        return $offersId;
    }


}


Przepraszam za chaotyczność jak coś to rozjaśnię. Czy coś jeszcze muszę zrobić żeby te dane mi wsadziło do tabeli ?

0

Nie kumam o co chodzi generalnie za dużo kodu w tym wszystkim. I złe praktyki. Zacznijmy po kolei od początku.

  1. Tworzysz tabele o nazwie: generator_logs
  2. Tworzysz model o nazwie: GeneratorLog
  3. Wrzucasz dane to tabeli:
 GeneratorLog::create([
             'allegro_account' => $name,
             'item_quantity' => $sets],
             'type' => $type,
        ]);

Dziękujemy dowidzenia

1 użytkowników online, w tym zalogowanych: 0, gości: 1