php - 提交第一篇文章后两个表之间的Laravel关系错误
问题描述
岗位型号:
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->size->name }}
解决方案
尝试更新您的模型,如下所示,您混淆了以下参数的顺序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'
推荐阅读
- java - 使用多边形创建形状无法正常工作 Java3d
- msmq - Microsoft 消息队列,系统时间为 2038 时未收到消息
- css - 如何在 nextcloud/vue 应用中使用谷歌字体
- cassandra - 一台 DC 停止同步。日志中的错误
- android - Android Instant 应用程序,为什么这些限制谁可以打开它们
- python - 用作类对象时出现 tkinter Listbox 错误
- ios - Facebook for Unity SDK (iOS) - 未找到 FBSDKCoreKit-Swift.h
- z3 - Z3Py:如何设置在 List 中声明的布尔变量?
- node.js - 使用 Node.Js 使用 shell 命令打开文件
- recharts - Recharts:堆叠多轴可能吗?