2017-06-12 87 views
0

什么是将stream_id作为外键保存在垃圾表内的最佳方法 我已经创建了这两个表的表。Laravel将外键保存在另一个表中

迁移:

public function up() 
{ 
    Schema::table('junk', function(Blueprint $table) 
    { 
     $table->integer('stream_id')->after('id')->unsigned(); 
    }); 
} 

控制器功能:

public function create(Request $request) 
{ 
    // create junk, junk shall contain the stream id as a foreign key (save in database) 
    $junk = new Junk(); 

    // stream information data -> the data is saved correctly here 
    $data = $request->all(); 
    $stream = new Stream(); 
    $stream->fill($data); 

    if($stream->save()) 
    { 
     return redirect()->route('stream.new')->with('success', 'saved.'); 
    } 
    else 
    { 
     return redirect()->route('stream.new')->with('error', 'not saved.')->withInput(); 
    } 
} 

我的垃圾型号:

public function junk() 
{ 
    return $this->belongsTo('Stream', 'junk_id'); 
} 

我流模型

public function stream() 
{ 
    return $this->belongsTo('Junk', 'stream_id'); 
} 

回答

0

如果你有relacionate模型的功能,可以让这个:

$junk = new Junk(); 
$junk->stream()->associate($request->all()); 

的关系:

  • 一对多,采用associate()方法
  • 多对多,用途attach()方法

有关Laravel(Eloquent ORM)中关系的更多信息

https://laravel.com/docs/5.4/eloquent-relationships#inserting-and-updating-related-models

+0

没有工作我把我的模型添加到quesiton头脑看看 – Olipol

+0

如果关系是一对一,方法是'hasOne()' – wbail

1

想要使用外键约束吗?如果是这样,你可以采取这种方法。下面是一个位置表的示例,其中包含坐标的外键:

public function up() 
{ 
    Schema::enableForeignKeyConstraints(); 

    Schema::create('location', function (Blueprint $table) { 
     $table->engine = 'InnoDB'; 
     $table->uuid('id'); 
     $table->primary('id'); 
     $table->uuid('coordinate_id')->nullable(); 
     $table->string('address')->nullable(); 
     $table->string('city')->nullable(); 
     $table->string('state')->nullable(); 
     $table->string('zipcode')->nullable(); 
     $table->timestamps(); 
    }); 

    Schema::table('location', function(Blueprint $table){ 
     $table->foreign('coordinate_id')->references('id')->on('coordinate'); 
    }); 
} 

没有对坐标表中位置的引用。

您不应该分配$ data = $ request-> all();你应该使用Validator类来保护自己不受大规模分配问题的影响。

这也很高兴看到你的垃圾类。

相关问题