在laravel中,我设置了外键,但它不起作用
我想在5.4版本的laravel中制作文件附件,但一对多关系不起作用 但它在用户关系中起作用 这是附件的来源在laravel中,我设置了外键,但它不起作用,laravel,Laravel,我想在5.4版本的laravel中制作文件附件,但一对多关系不起作用 但它在用户关系中起作用 这是附件的来源 public function up() { Schema::create('attachments',函数(Blueprint$table){ $table->increments('id'); $table->integer('article_id')->unsigned()->index(); $table->string('filename'); $table->integer
public function up()
{
Schema::create('attachments',函数(Blueprint$table){
$table->increments('id');
$table->integer('article_id')->unsigned()->index();
$table->string('filename');
$table->integer('bytes')->nullable()->unsigned();
$table->string('mime')->nullable();
$table->timestamps();
$table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')->onDelete('cascade');
});
}
创建附件时,需要添加文章id
。为此,您首先需要创建您的文章:
$article = $request->user()->articles()->create($request->all());
然后创建附件:
if($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file) {
$filename = str_random().filter_var($file->getClientOriginalName(), FILTER_SANITIZE_URL);
$file->move(public_path('files'), $filename);
$article = new \App\Article();
$article->attachments()->create([
'article_id' => $article->id,
'filename' => $filename,
'bytes' => $file->getClientSize(),
'mime' => $file->getClientMimeType()
]);
}
}
您正在进行某种插入/更新吗?显示这段代码。在附件表中,如果希望article\u id
为空,则将其设置为$table->integer('article\u id')->unsigned()->index()->nullable()代码>否则请确保在插入数据库时在项目id中输入值。我添加了控制器源代码