【发布时间】:2020-07-06 13:50:16
【问题描述】:
首先,我是一个初学者,我想尽我所能去学习。所以如果我有错误,请纠正我。
所以,我正在做一个 laravel 项目。我有两个模型;药物和相互作用。我正在苦苦挣扎的是,我想以一种形式添加两种药物和一种相互作用。而且,我想检查一下药物是否已经插入以避免重复数据。
这是我的模型:
class Drug extends Model
{
//Table Name
protected $table = 'drugs';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
//relationship
public function interactions()
{
return $this->belongsToMany('App\Interaction', 'drug_interaction', 'interaction_id', 'drug_id');
}
}
class Interaction extends Model
{
//Table Name
protected $table = 'interactions';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
//Relationship
public function drugs()
{
return $this->belongsToMany('App\Drug', 'drug_interaction', 'drug_id', 'interaction_id');
}
}
这只是我 DrugsController 中的存储功能
public function store(Request $request)
{
$this->validate($request, [
'name'=> 'required',
'info'=> 'nullable'
]);
//create drug
$drug = new Drug;
$drug->name = $request->input('name');
$drug->info = $request->input('info');
$drug->save();
return redirect('/drugs')->with('success', 'İlaç Eklendi');
}
这是我的 InterationsController 的存储功能。
public function store(Request $request)
{
$this->validate($request, [
'name'=> 'required',
'description'=> 'required',
'category'=> 'nullable'
]);
//create interaction
$interaction = new Interaction;
$interaction->name = $request->input('name');
$interaction->description = $request->input('description');
$interaction->category = $request->input('category');
$interaction->save();
我可以通过工匠修补程序附加关系,所以我认为关系有效。但是当涉及到多个输入表单到不同的控制器时,我坚持了下来。但是使用静态ID。我需要使它成为变量。但是两种药物应该与一种相互作用相关联。所以我无法同时从表单中成功传递两个变量。
用白话来说,我想要实现的是;
- 从表单的第一个文本框中请求 drug_name_one。检查 db 以获取该药物名称(如果存在);获取它的 ID。如果没有,则创建一个并获取 id。
- 从表单的第二个文本框中请求 drug_name_two。执行与第一步相同的操作。
- 创建在表单的第三个文本框中键入的交互。
- 附上它们。
PS:在这个 attach() 工作完成后,如果它们有共同的相互作用,我也找不到搜索两种药物的方法。如果您还可以提及一些技巧来实现这一点,我将不胜感激。
感谢所有帮助和进一步阅读建议。谢谢大家!
编辑:
这是 create_interactions 迁移。
Schema::create('interactions', function (Blueprint $table) {
$table->BigIncrements('id');
$table->string('name');
$table->string('description');
$table->string('category');
$table->timestamps();
});
}
这是“类别”字段的输入:
<div class="form-group">
{{Form::label('category', 'Kategori')}}
{{Form::text('category', '', ['class' => 'form-control', 'placeholder' => 'Etkileşim Kategorisi'])}}
</div>
顺便说一句,我无法制作我想要的表单结构。它只是一种没有关系的自行创建交互的形式。
【问题讨论】:
-
分类输入是什么类型的?
-
它是一个字符串,但它被设置为可以为空。
-
我现在迷失在这种关系附件中,我想我稍后会处理类别字段。
-
yh,如何保存关系显然是错误的,我需要知道输入的结构,但它是 id 还是名称?显示类别输入示例。
-
这是一个名字。我可以将其切换为下拉选择的可能性很小,但它仍将是一个名称。