如何在Laravel中插入行ID?

时间:2018-08-06 06:32:54

标签: laravel-5.4

我们创建了一个ID为56的学校桌子。

然后我们创建了一个ID = 1的活动表。

现在如何在活动表中保存school_id = 56。

我有问题。如何从学校表格中获取插入ID?

public function store(Request $request)
{
    if($request->ajax()) {
        $activity = new Activity();
        $activity->cluster_id = $request->cluster_id;
        $activity->group_id = $request->group_id;
        $activity->school_id = School::id;
        $activity->save();

        return response()->json(['data' => $request->all(), 'id' => $activity->school->id]);
    }
}

数据库

public function up()
{
    Schema::create('activities', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('school_id')->unsigned();
        $table->integer('cluster_id')->unsigned();
        $table->integer('group_id')->unsigned();
        $table->timestamps();

        $table->foreign('school_id')->references('id')->on('schools');
        $table->foreign('cluster_id')->references('id')->on('clusters');
        $table->foreign('group_id')->references('id')->on('groups');
    });
}

型号

class Activity extends Model
{
    public function school()
    {
        return $this->belongsTo(SchoolsList::class);
    }
}

1 个答案:

答案 0 :(得分:0)

假设您的School Model保存方法如下:

 $school = new School;
 $school->title = 'Baghoon High School';
 $school->location= 'Bangladesh';
 $school->save();

然后您要运行此代码

if($request->ajax()) {
    $activity = new Activity();
    $activity->school_id = $school->id;
    $activity->save();
    return response()->json(['data' => $request->all(), 'id' => $school->id]);
}