Laravel雄辩 - 一起插入相关表格

时间:2016-01-11 10:33:58

标签: mysql laravel-5 eloquent

我搜索了这个并得到了很多结果,每个人都说它有效。

我的情况与此处http://laravel.io/forum/04-22-2015-hasone-and-insert

完全相同
Schema::create('devices', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('token')->unique();
        $table->enum('type', ['android', 'ios']);
        $table->timestamps();

    });
Schema::create('students', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('nom', 15);
        $table->integer('device_id')->unsigned();
        $table->timestamps();

        $table->foreign('device_id')->references('id')->on('devices')->onDelete('cascade');
    });

学生模特

public function device() {
    return $this->hasOne('App\Device');
}

设备型号

public function user()
{
    return $this->belongsTo('App\Etudiant');
}

我试过

$student = Student::create(['nom' => $nom, 'type' => $type]);
$student->device()->create(['token' => $token]);
$student->save();

但我收到Call to undefined method Illuminate\Database\Query\Builder::create()

的错误$student->device()->create(['token' => $token]);

1 个答案:

答案 0 :(得分:0)

知道了!

 $post = (new Student)->fill(['name'=>'robin'])
                ->device()->associate(Device::create(['token' => 'TOKEN']))
                ->save();

参考:laravel Eloquent ORM multiple table insert