laravel迁移更改未反映

时间:2020-07-22 20:24:44

标签: php laravel

在图像迁移中,我将post_id外键更改为posts_id,以使关系正常工作。但是,更改后,在图像表中插入图像仍在选择post_id,这给了我一个未找到错误列的信息。我尝试过cache:clear和config,但没有任何效果。 post_id在我的代码中不存在

后控制器

 public function store( Request $request )
{    
    $data = request()->validate([
        'user_id' => 'required',
        'about' => 'required',
        'category' => '',
        'expire_date' => '',
        

    ]); 
if (Auth::guard('web')->check())
     {
       $user = Auth::user();
       $post = new Post();

       /*$post = $user->posts()->create([
            'about' => $data['about'],
            'category' => $data['category'],
            'expire_date' => $data['expire_date'],
            
        ]);*/
        if($request->hasFile('image'))
        {
          $files = $request->file('image');
          
          
          
          foreach($files as $file)
          {
            
            $name = time().'-'.$file->getClientOriginalName();
            $name = str_replace('','-',$name);
            echo $name;
            
            $file->move('images',$name);
            
            $post->images()->create(['image' => $name ]);
           

          }
        }
       


        $user = Auth::guard('web')->id() ;

        return redirect()->route('home',['user'=>$user]);

        
    }


  }

postmodel

public function posts()
{
    return $this->belongsTo(User::class);
}

图像模型

class images extends Model
{

    protected $fillable = [
    'posts_id',
    'image'
];
 
public function posts(){
    return $this->belongTo(Posts::class);

}
}

发布迁移信息

 public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->uuid('user_id')->nullable;
        $table->uuid('admin_id')->nullable;
        $table->string('category')->nullable;
        $table->string('about');
       
        $table->timestamps();
    });
}

图像迁移

public function up()
{
    Schema::create('images', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('posts_id');
        $table->string('image');
        $table->timestamps();
        
        $table->index('posts_id');

    });
}

2 个答案:

答案 0 :(得分:0)

尝试更改图片模型

public function posts(){
    return $this->belongTo(Posts::class);
}

public function posts(){
    return $this->belongTo(Posts::class, 'posts_id');
}

答案 1 :(得分:0)

为什么要更改它?如果将Laravel留给post_id,它可以为您处理。否则,您必须通过添加额外的参数来更新图像模型中的关联帖子。请参阅文档:laravel.com/docs/7.x/eloquent-relationships

public function posts(){
    return $this->belongTo(Posts::class, 'posts_id');
}