0

I have Checklists and Alats Table that has a relationship like this:

1 data in Checklists can have many data in Alats (ex: IDC001 in Checklists can have IDA001, ID002, and ID003 in Alats)

The question is, how do you insert all those data into IDC001? especially how do you do it in Eloquent (laravel 6)

agastyarimbawa
  • 59
  • 1
  • 1
  • 4

1 Answers1

0

For this task we need to implement one To Many relationship.

In your Checklist model you need to define

<?php

  namespace App;
  use Illuminate\Database\Eloquent\Model;

  class Checklist extends Model
  {
    public function alats()
    {
        return $this->hasMany('App\Alat');
    }
  }

which means CheckList has many Alat models.

Now,in your Alat model you need to define

  namespace App;
  use Illuminate\Database\Eloquent\Model;

  class Alat extends Model
  {

    public function checklist()
    {
       return $this->belongsTo('App\Checklist');
    }
  }

which means Alat has a relationship with CheckList model.

Usage:To save multiple records, need to use saveMany()

$alats = App\Checklist::where('column_name_of_checklists_table', 'IDC001')->first()->alats;

$alats->saveMany([
       new App\Alat(['column_name_of_alats_table' => 'IDA001']),
       new App\Alat(['column_name_of_alats_table' => 'ID0002']),
       new App\Alat(['column_name_of_alats_table' => 'ID0003']),
   ]);
Md. Amirozzaman
  • 1,083
  • 10
  • 21
  • I kinda confused here, so what saveMany() do to IDA001, etc, is inserting it to alats table, am I right? but the thing is, I want them to be inserted into checklists table, so that 1 row of checklist table can have IDA001, IDA002, IDA003 simultaneously – agastyarimbawa Jan 10 '20 at 19:56
  • Yes,you are right.Now if you want to insert them in `checklists` table,then what is purpose of `alats` table? – Md. Amirozzaman Jan 10 '20 at 19:59
  • I'm confused in how this relationship works. I've made a research about one to many relationship, so in my case, (cmiiw) in alats table, every row has a column named 'layanan_name' that referencing 'id' in layanans table, and a column named 'locations' that referencing to 'id' in locations table. Now, when I want to create a new data for 'checklist' table, the form would need you to choose what layanan and location you want to create a checklist – agastyarimbawa Jan 11 '20 at 04:11
  • ex: I want to create a checklist that has layanan A and location 'bedroom', then the query would search every 'alats' that has layanan A and location 'bedroom', so if there are 3 'alats' that has layanan A and location 'bedroom', it will be displayed as checklist 1 that i want to create in the first time – agastyarimbawa Jan 11 '20 at 04:11