我需要将相同的数据传递给2个表(prospect和course_prospect)
这是我的职责
public function store(Request $request) {
$prospect = new Prospect;
$prospect->prospect_name = $request->prospect_name;
$prospect->prospect_nic = $request->prospect_nic;
$prospect->contact_number = $request->contact_number;
$prospect->address = $request->address;
$value = implode(',', $request->course_intrested);
$prospect->course_intrested = $value;
$prospect->comments = $request->comments;
$prospect->referred_through = $request->referred_through;
$selected_courses = new Prospect;
$course_prospect = new Course_prospect;
$course_prospect->course_id = $value;
$course_prospect->prospect_id = $selected_courses->id;
$course_prospect->save();
$prospect->save();
return redirect()->back();
}
和course_prospect表具有2个外键(course_id和准客户ID)
这是course_prospect迁移
Schema::create('course_prospect', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('prospect_id')->unsigned();
$table->integer('course_id')->unsigned();
$table->timestamps();
});
Schema::table('course_prospect', function($table) {
$table->foreign('prospect_id')->references('id')->on('prospect')-
>onDelete('cascade');
$table->foreign('course_id')->references('course_id')-
>on('course')->onDelete('cascade');
});
但是当我提交仅具有数据的表单潜在客户表时。我认为外键不起作用
答案 0 :(得分:0)
我不确定您的逻辑,但请注意以下内容:
$selected_courses = new Prospect;
您正在创建一个新对象。 当您拨打此行时:
$course_prospect->prospect_id = $selected_courses->id;
$ selected_courses-> id为NULL;
我认为您正在尝试使用ManyToMany关系...
所以正确的方法是这样做:
公共功能存储区(请求$ request){
$prospect = new Prospect;
$prospect->prospect_name = $request->prospect_name;
$prospect->prospect_nic = $request->prospect_nic;
$prospect->contact_number = $request->contact_number;
$prospect->address = $request->address;
$value = implode(',', $request->course_intrested);
$prospect->course_intrested = $value;
$prospect->comments = $request->comments;
$prospect->referred_through = $request->referred_through;
//保存潜在客户并从数据库获取ID
$ prospect-> save();
$ prospect-> courses()-> sync($ request-> course_intrested);
return redirect()->back();
}
假设您已定义了Prospect和Course模型中的ManyToMany关系,则这将填充course_prospect表。
在此处了解更多信息: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many