我在映像迁移中将post_id外键更改为posts_id,以使关系正常工作。然而,更改后,图像表中图像的插入仍然拾取post_id,这会给我一个错误列not found。我尝试了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]);
}
}后模型
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');
});
}发布于 2020-07-23 04:30:06
尝试更改图像模型
public function posts(){
return $this->belongTo(Posts::class);
}至
public function posts(){
return $this->belongTo(Posts::class, 'posts_id');
}发布于 2020-07-23 04:34:29
你为什么要改变它呢?如果交给post_id,Laravel可以为你处理这件事。否则,您将不得不通过添加额外的参数来更新图像模型中的关系帖子。请参阅文档: laravel.com/docs/7.x/eloquent-relationships
public function posts(){
return $this->belongTo(Posts::class, 'posts_id');
}https://stackoverflow.com/questions/63042638
复制相似问题