当我发送外键时,Laravel Eloquent不能插入行?

时间:2015-07-28 18:21:14

标签: php mysql laravel eloquent

这是控制器中的方法:

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插入第一行没有问题,但第二个寄存器没有,在新的通知中不要插入如果$ ad-> id但是如果发送一个harcode值,如' 4'插入成功了,发生了什么事呢?

通知迁移:

<?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');
    }
}

这是模型:

<?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');
    }
}

1 个答案:

答案 0 :(得分:1)

我相信你的onDelete('cascade')搞砸了你。

创建Notification后,立即致电$ad->delete()。但您的迁移包含:

  

$table->foreign('ad_id')->references('id')->on('ads')->onDelete('cascade');

这意味着当广告被删除时,通知也会被删除。