【发布时间】:2018-03-28 07:18:35
【问题描述】:
我是 Laravel 的新手。我想要这样:
当我存储正确存储在多个表中的数据时。存储后,它还将具有 disease_symptoms_medicines 表(外键)上所有三个表的 id。我不知道该怎么做。
在这段代码中没有错误。
这是我的迁移:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDiseasesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('diseases', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('slug')->nullable();
$table->text('description')->nullable();
$table->text('symptoms')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('diseases');
}
}
症状迁移
public function up()
{
Schema::create('symptoms', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
药物迁移
public function up()
{
Schema::create('diseases', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->nullable();
$table->string('slug')->nullable();
$table->text('description')->nullable();
$table->text('symptoms')->nullable();
$table->timestamps();
});
}
为附加疾病、症状和医学的外键创建
疾病模型
class Disease extends Model
{
protected $table ='diseases';
public function symptoms(){
return $this->belongsTo('App\Symptoms');
}
public function medicines(){
return $this->belongsTo('App\Medicine');
}
症状模型
class Symptoms extends Model{
protected $table ='symptoms';
public function diseases()
{
return $this->hasMany('App\Disease');
}
}
医学模型
class Medicine extends Model{
protected $table ='medicines';
public function diseases(){
$this->hasMany('App\Disease');
}
}
这是我的控制器
public function store(Request $request)
{
$disease=new Disease;
$disease->name=$request->input('name');
$disease->slug=$request->input('slug');
$disease->description=$request->input('description');
$disease->save();
$symptom=new Symptoms;
$symptom->name=$request->input('symtom');
$symptom->save();
$medicine=new Medicine;
$medicine->name = $request->input('medic');
$$medicine->save();
return redirect()->back();
}
【问题讨论】:
-
要记住的一件事;尝试给你的模型命名单数而不是复数。你已经为
Disease和Medicine这样做了,但不是Symptoms。保持一致将使以后的事情更容易管理。 -
好的,我下次再做。
-
您的帖子中有各种拼写错误,这是一回事,但您的拼写错误正在泄漏到您的代码中。您有一个名为
symtom的控件,但模型拼写正确 - 它有一个“p”。这种差异是另一个一致性问题,可能会在以后给您带来困难。
标签: php laravel eloquent foreign-keys