在laravel我设置foriegn键但它不起作用

时间:2017-10-28 09:36:42

标签: laravel

我想在5.4中的laravel中创建文件附件,但是一对多的关系不起作用。

但它适用于文章 - 用户关系

是附件来源

    public function up()
    {
        Schema::create('attachments', function (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');
        });
    }

这是文章来源

   public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('title');
            $table->text('content');
            $table->string('image');
            $table->string('file');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
        });
    }

是文章模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title', 'content'];
    public function user()
        {
                return $this->belongsTo(User::class);
        }


        public function attachments()
        {
        return $this->hasMany(Attachment::class);
        }
}

是附件模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attachment extends Model
{
        protected $fillable = ['filename', 'bytes', 'mime'];
        public function article()
        {
        return $this->belongsTo(Article::class);
        }
        public function getBytesAttribute($value)
        {
                return format_filesize($value);
        }
        public function getUrlAttribute()
        {
                return url('files/'.$this->filename);
        }
}

,错误是

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into `attachments` (`filename`, `bytes`, `mime`, `article_id`, `updated_at`, `created_at`) values (aMqJUvEaLpXrAtKOre().docx, 111207, application/octet-stream, , 2017-10-28 09:33:32, 2017-10-28 09:33:32))

文章 - 用户链也有效,但不是文章 - 附件...... 请帮助我...坦克阅读。

  • 这是我的插入代码(ArticleController)-so messy ..

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
class ArticlesController extends Controller
{

    public function index()
    {
//        $articles = \App\Article::with('user')->get();
          $articles = \App\Article::latest()->paginate(5);
        return view('pages.article', compact('articles'));
    }


    public function create()
    {
        return view('pages.articlecreate');
    }

    public function store(Request $request)
    {
        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([
                                'filename' => $filename,
                                'bytes' => $file->getClientSize(),
                                'mime' => $file->getClientMimeType()
                        ]);
                }
        }
        $rules = [
                'title' => ['required'],
                'content' => ['required', 'min:10'],
        $validator = \Validator::make($request->all(), $rules);
        if ($validator->fails()){
        return back()->withErrors($validator)->withInput();}
        $article = $request->user()->articles()->create($request->all());
        if(! $article) {
          return back()->with('flash_message', 'FAILD.')->withInput();
        }
        return redirect(route('articles.index'))->with('flash_message', 'SAVED.');
    }


    public function show(\App\Article $article)
    {
        //
        return view('pages.articleshow', compact('article')); //171021
    }

    public function edit(\App\Article $article)
    {
        return view('pages.articleedit', compact('article')); //171022
    }


    public function update(Request $request, \App\Article $article)
    {
        $article->update($request->all());
        return redirect(route('articles.show', $article->id));
    }

    public function destroy(Request $request, \App\Article $article)
    {
        $article->delete($request->all());
        return redirect('articles');
    }
}

1 个答案:

答案 0 :(得分:1)

您需要在创建article_id时添加attachment。为此,您首先需要创建文章:

$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()
       ]);
   }
}