Laravel - недавно вставленная красноречивая последовательность идентификаторов - PullRequest
1 голос
/ 02 мая 2019

У меня есть две модели, новости и редакционные статьи. Когда я заполняю БД 50 новостями и 4 редакционными статьями, идентификаторы новостей и редакционных статей располагаются в последовательном порядке, то есть 1, 2, 3 и т. Д. Но после того, как я вставляю новость или редакционную статью через форму пользователя, следующий идентификатор новостей устанавливается на 55, который должен быть 51. и при добавлении передовой статьи следующий идентификатор равен 56, когда это должно быть 5, поскольку последний редакторский идентификатор равен 4. Я пытаюсь выяснить, что является причиной этой странной проблемы.

News Seeder

class NewsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Models\News::class,50)->create()->each(
            function($news){
                $faker = Faker::create();

                //---------create one category------------
                $category_array =['Women & Children','Minority', 'Free Speech', 'Democracy'];
                $randomCategory = array_rand($category_array);
                $category= new Category();
                $category->description = $category_array[$randomCategory];
                $category->save();

                $news->category()->associate($category);

                //---------create multiple tags -----------
                    $randomCounter = rand(1,3);
                    $tag_array =['Politics','Environment','Hate Speech', 'Weather'];
                    for ($i=0; $i<$randomCounter ; $i++) {
                        $tag = new Tag();
                        $tag->description = $tag_array[$i];
                        $news->tags()->save($tag);

                    }//end for
                //------- create multiple tags-------------

                //------- create multiple comments for this news------------
                    $randomCounter= rand(1,10);
                    for ($i=0; $i<$randomCounter ; $i++) {
                        $comment                = new Comment();
                        $comment->user_name     = $faker->name();
                        $comment->email         = $faker->safeEmail();
                        $comment->title         = $faker->sentence(rand(2,3));
                        $comment->content       = $faker->paragraph(rand(10,15));
                        $comment->status          ='Approved';
                        $comment->news_id       =$news->id;
                        //$comment->save();

                        $news->comments()->save($comment);

                    }//end for
            }//end inner function
        );
    }
} 

Редактор Сеялка

class EditorialTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(App\Models\Editorial::class,4)->create()->each(
            function($editorial){
                $faker = Faker::create();

                //---------create one category------------
                $category_array =['Women & Children','Minority', 'Free Speech', 'Democracy'];
                $randomCategory = array_rand($category_array);
                $category= new Category();
                $category->description = $category_array[$randomCategory];
                $category->save();

                $editorial->category()->associate($category);

                //---------create multiple tags -----------
                    $randomCounter = rand(1,3);
                    $tag_array =['Politics','Environment','Hate Speech', 'Weather'];;
                    for ($i=0; $i<$randomCounter ; $i++) {
                        $tag = new Tag();
                        $tag->description = $tag_array[$i];
                        $editorial->tags()->save($tag);

                    }//end for
                //------- create multiple tags-------------

                //------- create multiple comments for this news------------
                    $randomCounter= rand(1,10);
                    for ($i=0; $i<$randomCounter ; $i++) {
                        $comment                = new Comment();
                        $comment->user_name     = $faker->name();
                        $comment->email         = $faker->safeEmail();
                        $comment->title         = $faker->sentence(rand(2,3));
                        $comment->content       = $faker->paragraph(rand(10,15));
                        $comment->status          ='Approved';
                        $comment->editorial_id       =$editorial->id;

                        $editorial->comments()->save($comment);

                }//end for
            }
        );
    }
}


Способ сохранения контроллера новостей

public function store(Request $request)
{
    //validate the data
    $validator = Validator::make($request->all(), [
        'news_title' => 'required|min:20|max:150',
        'news_short_desc' => 'required|max:250|min:10',
        'news_story' => 'required|max:2500|min:10',
    ]);

    //if validation fails laravel will automatically redirect to previous page
    $validator->validate();

    //validation successful proceed with saving the record
    //and also add record to linked/ junction tables
    $news = new News;
    $news->title = $request->news_title;
    $news->short_desc = $request->news_short_desc;
    $news->story = $request->news_story;
    $news->image_path = url('/') . $request->filepath;

    if ($request->has('is_featured')) {
        $news->is_featured = 'Y';
    } else {
        $news->is_featured = 'N';
    }

    //check dropdown inputs
    $category = new Category();

    switch ($request->input('news_category')) {
        case 'w':
            //$news->category_id= 1;
            $category->description = 'Women & Children';
            $category->save();
            //add record to link table
            $news->category()->associate($category);
            break;

        case 'm':
            //$news->category_id= 2;
            $category->description = 'Minority';
            $category->save();
            //add record to link table
            $news->category()->associate($category);
            break;

        case 'f':
            //$news->category_id= 3;
            $category->description = 'Free Speech';
            $category->save();
            //add record to link table
            $news->category()->associate($category);
            break;

        case 'd':
            // $news->category_id= 4;
            $category->description = 'Democracy';
            $category->save();
            //add record to link table
            $news->category()->associate($category);
            break;
    } //end switch

    $news->posted_by = auth('admin')->user()->name;

    $news->save();

    //create Tags
    $tag_array = LogicHelper::getTagList();

    for ($i = 0; $i <= count($tag_array); $i++) {
        if (($request->has('tag_' . ($i + 1)))) {
            $tag = new Tag();
            //create new tag
            $tag->description = $tag_array[$i];
            // $tag->save();
            $news->tags()->save($tag);
        } //end if
    }//end for

    Session::flash('add_success', 'News Added Successfully!');
    return redirect()->route('add.news');
}//end method 

Редакционный метод сохранения

public function save(Request $request){
    //validate the data
    $validator = Validator::make($request->all(), [
        'title' => 'required|min:20|max:150',
        'short_desc' => 'required|max:190|min:10',
        'content' => 'required|max:2500|min:10',

    ]);

    //if validation fails laravel will automatically redirect to previous page
    $validator->validate();
    //check if at least one image exists!

    //validation successful proceed with saving the record
    //and also add record to linked/ junction tables
    $editorial = new Editorial();
    $editorial->title= $request->title;
    $editorial->short_description= $request->short_desc;
    $editorial->content= $request->content;
    //check dropdown inputs
    $category = new Category();

    switch ($request->input('category')) {
        case 'w':
            //$editorial->category_id= 1;
            $category->description = 'Women & Children';
            $category->save();
            //add record to link table
            $editorial->category()->associate($category);
            break;

        case 'm':
            // $editorial->category_id= 2;
            $category->description = 'Minority';
            $category->save();
            //add record to link table
            $editorial->category()->associate($category);
            break;

        case 'f':
            //$editorial->category_id= 3;
            $category->description = 'Free Speech';
            $category->save();
            //add record to link table
            $editorial->category()->associate($category);
            break;

        case 'd':
            //$editorial->category_id= 4;
            $category->description = 'Democracy';
            $category->save();
            //add record to link table
            $editorial->category()->associate($category);
            break;
    }//end switch

    $editorial->image_path= url('/').$request->filepath;

    $editorial->posted_by= auth('admin')->user()->name;

    $editorial->save();

    Session::flash('add_success','Editorial Created Successfully!');
    return redirect()->route('add.editorial');

}//end method
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...