简体   繁体   中英

insert data using current value from another table laravel?

so i have 2 tables, that is Hewan as parent and Ras_Hewan as child. there's some data on my parent table, i want to insert value to my child table using current value from parent table without form?

Parent table

protected $fillable = [
    'nama_jenis_hewan',
    'parent_id',
    'slug_jenis_hewan'
];

public function rasHewan() {
    return $this->hasMany(RasHewan::class,'id');
}

public function getNamaJenisHewan() {
    return $this->hasOne(RasHewan::class,'id','nama_ras_hewan')
}

Child table

use HasFactory;
public $timestamps = false;
protected $fillable = [
    'nama_ras_hewan',
    'jenis_hewan_id',
    'slug_ras_hewan'
];


public function ParentJenisHewan() {
    return $this->belongsTo(JenisHewan::class,'jenis_hewan_id','id');
}

public function NamaJenisHewan() {
    return $this->belongsTo(JenisHewan::class,'jenis_hewan_id','nama_ras_hewan');
}

insert function

public function store(Request $request)
    {   
      $getParentOption = JenisHewan::where('id')->pluck('nama_jenis_hewan');
    
            $validator = $request->validate([
                'nama_ras_hewan'        => 'required|string|min:3',
                'jenis_hewan_id'        => 'required|string|',
                'parent_ras_jenis_hewan'=> 'string', 
            ], [
                'nama_ras_hewan.required' => 'Ras Hewan tidak boleh kosong']
            );
            RasHewan::create($validator);   
            
            if(validator()) {
                return redirect()->route('rashewan.index')
                                 ->with('success', 'Data '.$request->nama_ras_hewan .' telah selesai dibuat.');
            } else {
                return redirect()->route('rashewan.index')->with('error','Data gagal dibuat');
            }
        }

it is just like,when it's data insert in my child table,it will automatically use "nama_jenis_hewan" value from my parent table?

Normally elocuent give you an aproach for this when relationships are present. If in your request have the parent selected then for create the child throught the relationship can be done like:

$getParentOption = JenisHewan::where('id',$request->get('id'))->first();
$validator = $request->validate([
   'nama_ras_hewan'        => 'required|string|min:3',
   'parent_ras_jenis_hewan'=> 'string', 
   ], [
        'nama_ras_hewan.required' => 'Ras Hewan tidak boleh kosong']
);
$getParentOption->rasHewan()->create($validator);   
   //.............

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM