[英]insert data using current value from another table laravel?
so i have 2 tables, that is Hewan as parent and Ras_Hewan as child.所以我有 2 张桌子,即 Hewan 作为父母,Ras_Hewan 作为孩子。 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插入 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?就像,当它在我的子表中插入数据时,它会自动使用我父表中的“nama_jenis_hewan”值?
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);
//.............
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.