gpt4 book ai didi

php - 当我发送外键时,Laravel Eloquent 无法插入行?

转载 作者:行者123 更新时间:2023-11-29 12:04:54 25 4
gpt4 key购买 nike

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

通知迁移:

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

最佳答案

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

创建通知后,您立即调用$ad->delete()。但您的迁移包含:

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

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

关于php - 当我发送外键时,Laravel Eloquent 无法插入行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31684230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com