2017-06-12 86 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類來保護自己不受大規模分配問題的影響。

這也很高興看到你的垃圾類。

相關問題