[英]Laravel Eloquent can't insert row when i send a foreign key?
This is the method in the controller: 这是控制器中的方法:
public function buyConfirm($ad_id)
{
$ad = Ad::find($ad_id);
$sale = new Sale;
$sale->ad_id = $ad->id;
$sale->seller_id = $ad->user->id;
$sale->buyer_id = \Auth::user()->id;
$sale->save();
$x = new Notification;
$x->ad_id = $ad->id;
$x->user_id = $ad->user->id;
$x->type = 'bought';
$x->view = 0;
$x->save();
$ad->delete();
return \Redirect::route('buyContact',$sale->id)->with('message', 'Done');
}
Laravel insert the first row without problems, but the second register not, in the new Notification dont insert if $ad->id but if a send a harcode value like '4' the insert is successfully, what happend whit this? Laravel插入第一行没有问题,但是第二个寄存器没有问题,如果$ ad-> id不会在新Notification中插入,但是如果成功发送了像“ 4”这样的harcode值,插入成功了,这是怎么回事?
The Notification migration: 通知迁移:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotificationsTable extends Migration
{
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->string('type');
$table->integer('user_id')->unsigned();
$table->integer('ad_id')->unsigned();
$table->boolean('view');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
});
}
public function down()
{
Schema::drop('notifications');
}
}
This is the model: 这是模型:
<?php namespace Telovendogdl;
use Illuminate\Database\Eloquent\Model;
class Notification extends Model
{
protected $table = 'notifications';
protected $fillable = ['type','ad_id','user_id','view'];
public function user()
{
return $this->belongsTo('App\User');
}
public function ad()
{
return $this->belongsTo('App\Ad');
}
}
I believe your onDelete('cascade')
is messing you up. 我相信您的onDelete('cascade')
您onDelete('cascade')
。
Right after creating the Notification
, you call $ad->delete()
. 创建Notification
,立即调用$ad->delete()
。 But your migration contains: 但是您的迁移包含:
$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');
This means that when an ad is deleted, the notification is also deleted. 这意味着删除广告后,通知也将被删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.