gpt4 book ai didi

php - Laravel 外键保存问题

转载 作者:行者123 更新时间:2023-11-29 10:49:22 24 4
gpt4 key购买 nike

我有名为 companies 的表和其他名为 ads 的表,我尝试在名为 company_id 的广告列中获取公司 ID。

这是我的广告迁移:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateAdTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('ads', function (Blueprint $table) {
$table->increments('id');
$table->integer('company_id')->unsigned();
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('image')->nullable();
$table->string('description');
$table->timestamps();
});

Schema::table('ads', function($table) {
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('ads');
}
}

这将毫无问题地创建我的广告表,但当我尝试保存广告时,它会返回此错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jobid`.`ads`, CONSTRAINT `ads_company_id_foreign` FOREIGN KEY (`company_id`) REFERENCES `companies` (`id`)) (SQL: insert into `ads` (`title`, `slug`, `description`, `image`, `updated_at`, `created_at`) values (first ad test, first-ad-test, <p>rwv R4QF Q4R</p>, 1494998776.png, 2017-05-17 12:26:17, 2017-05-17 12:26:17))

我该如何解决这个问题?

更新

public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->string('manager_name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('image')->nullable();
$table->string('password');
$table->text('about')->nullable();
$table->rememberToken();
$table->timestamps();
});
}

商店功能

  public function store(Request $request)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|alpha_dash|min:5|max:255|unique:ads,slug',
'image' => 'sometimes|image',
'description' => 'required'
));

$ad = new Ad;

$ad->title = $request->input('title');
$ad->slug = $request->input('slug');
$ad->description = $request->input('description');


if ($request->hasFile('image')) {
$avatar = $request->file('image');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('ads/');
$request->file('image')->move($location, $filename);


$ad->image = $filename;
}

$ad->save();


Session::flash('success', 'Your ad published successfully!');

return redirect()->route('company.adslist', $ad->id);
}

最佳答案

in your company form
<input type="hidden" name="company_id" value ="{{ company_id }}">

然后是存储方法

  $ad->company_id=Input::get('company_id');

你可以根据用户输入使id动态化,我暂时只是硬编码

关于php - Laravel 外键保存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44016405/

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