在这里我试图通过使用关系来获取类别的名称 到目前为止,我所做的是在我的产品模型中定义了这样的关系
Public function category()
{
return $this->belongsto(Category::class);
}
我还存储了字段类别id 在我的产品表中
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('Category_id');
$table->string('name');
$table->string('code');
$table->string('color');
$table->string('description');
$table->double('price');
$table->integer('quantity');
$table->string('image');
$table->timestamps();
});
我还在我的类别模型中定义了一个关系,例如
public function product()
{
return $this->hasmany(Product::class);
}
我还定义了关系 产品作为
Public function category()
{
return $this->belongsto(Category::class);
}
在我看来,我正在尝试获取类别的名称
@foreach($products as $pro)
<tr>
<td><img src="{{asset('uploads/maj/'.$pro->image)}}" class="img-circle" alt="User Image" width="50" height="50"> </td>
<td>{{$pro->category->name}}</td>
<td>{{$pro->name}}</td>
<td>{{$pro->code}}</td>
<td>{{$pro->color}}</td>
<td>{{$pro->description}}</td>
<td>{{$pro->price}}</td>
<td>{{$pro->quantity}}</td>
我收到错误
Trying to get property 'name' of non-object
如何获取类别的名称?? 我正在尝试这样获取它,但这会出错
{{$pro->category->name}}
类别表行
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->String('Parent_id');
$table->string('name');
$table->string('status');
$table->timestamps();
});
我的 laravel 版本是 7 谢谢
最佳答案
可能一个或多个产品没有类别或 category_id 错误。
您可以使用条件来检查类别是否不存在:
{{$pro->category ? $pro->category->name : "no category"}}
或者可以简单地使用空合并运算符:
{{$pro->category->name ?? "no category"}}
如果需要类别,您应该通过添加表关系/外部来阻止它。
https://stackoverflow.com/questions/64408858/
相关文章:
.htaccess - 使用指向 page.php 的 1 个参数编写干净的 URLS
html - 空白 nowrap 但如果大于 css 中的最大宽度则换行
python - 如何在 Python 中删除 .txt 文件的前几行?
github - 使用另一个存储库的 github 操作工作流文件
javascript - 浏览器客户端如何在没有像 Apollo 或 Relay 这样的库的情况下使
ruby-on-rails - "Could not find concurrent-ruby-1.
docker - 每个命令都会导致 fatal error : runtime: out of me
node.js - MongoDB-Memory-Server 使 jest 测试调试卡在 WSL