Laravel提交第一篇文章后两个表之间的关系错误



Post Model:

class Post extends Model
{
protected $fillable = [
'name',
'image',
'genders_id',
'categories_id',
'sizes_id',
'price'
];
public function category()
{
return $this->hasOne(Category::class, 'id');
}
public function gender()
{
return $this->hasOne(Gender::class, 'id');
}
public function size()
{
return $this->hasOne(Size::class, 'id');
}
}

index.blade.php:

@foreach ($posts as $post)
<td><img src="{{ url('storage/'. $post->image) }}" width="100" height="50"></td>
<td>{{ $post->name }}</td>
<td>{{ $post->size->name }}</td>
<td>{{ $post->category->name }}</td>
<td>{{ $post->gender->name }}</td>
<td>{{ $post->price }} $</td>
<td></td>
</tbody>
@endforeach

帖子表:

public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('genders_id');
$table->string('sizes_id');
$table->string('categories_id');
$table->integer('price');
$table->string('image');
$table->timestamps();
});
}

帖子控制器:

public function store(PostValidation $request)
{
$image = $request->file('image')->store('image');
Post::create([
'name' => $request->name,
'image' => $image,
'genders_id' => $request->gender,
'categories_id' => $request->categories,
'sizes_id' => $request->size,
'price' => $request->price
]);
return redirect(route('post.index'));
}

问题是{{ $post->size->name }}{{ $post->gender->name }}{{ $post->category->name }}在我的第一篇文章之后工作,每当我添加第二篇帖子时,它都会给我以下错误:

尝试获取非对象的属性"名称"(查看: C:\xampp\htdocs\PracticeOnly\resources\views\posts\index.blade.php( {{ $post->大小->名称 }}

尝试像下面这样更新模型,您在hasOne()中混淆了参数的顺序:

class Post extends Model
{
protected $fillable = [
'name',
'image',
'genders_id',
'categories_id',
'sizes_id',
'price'
];
public function category()
{
return $this->hasOne(Category::class,'categories_id');
}
public function gender()
{
return $this->hasOne(Gender::class,'genders_id');
}
public function size()
{
return $this->hasOne(Size::class,'sizes_id');
}
}

一对多关系的标准命名方案是单数列名:

'genders_id' => 'gender_id'
'categories_id' => 'category_id'
'sizes_id' => 'size_id'

运行php artisan tinker通过$post = Post::find({{id}})找到您的帖子,然后尝试通过$size = $post->size访问其大小属性。

您应该收到null,即您的帖子/尺寸模型关系从未建立过。

确认后,运行$post->size_id以检查是否在请求中设置了此设置,如果没有,则未在请求中正确传递 size 属性。

否则,我建议您检查关系中的外键是否与您的表名匹配(尤其是在size中(,您可能已经使用 Size 类中的$table属性覆盖了模型中的表名。

相关内容

最新更新