php - 在 Laravel 7 中调用模型 [App\Category] 上的未定义关系 [products]
问题描述
我正在使用 larvel 7 创建一个简单的库存系统。我遇到了问题
Call to undefined relationship [products] on model [App\Category].
我正在创建一个两个表类别,并且我想要与它们有关系的产品。
类别表
id categoryname
1 drink
2 biscuits
3 toy
产品表
id productname category
1 fanta 1
2 apple juice 1
3 buildblocks 3
我需要将类别表和产品表看起来像这样并获取数据并传递给表。我需要以下输出:
id productname categoryname
1 fanta drink
当我运行程序时,我收到了这个错误:
Call to undefined relationship [products] on model [App\Category].
我不知道为什么它发生了。到目前为止我尝试了什么,我附在下面。
模型
类别
class Category extends Model
{
protected $fillable = [
'categoryname',
];
}
产品
class Product extends Model
{
protected $fillable = [
'product_name',
'category',
];
public function category (){
return $this->belongsTo('App\Models\Category','category','id');
}
}
view.blade.php
<tbody>
@foreach ($products as $key => $product)
<tr>
<td>{{$key}}</td>
<td>{{$product->product_name}}</td>
<td>{{$product->category->categoryname}}</td>
</tr>
@endforeach
</tbody>
路线
Route::get('/products', 'ProductController@view')->name('product.view');
产品控制器
<?php
namespace App\Http\Controllers;
use App\Product;
use App\Category;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function view()
{
$products = Product::with('category')->get();
dd($products);
$categories = Category::with('products')->get();
return view ('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
}
解决方案
在您的类别模型中,您还必须添加反向关系,因为您在要检索类别列表时使用它。
类别型号:
class Category extends Model
{
protected $fillable = [
'categoryname',
];
public function products (){
return $this->hasMany('App\Models\Product','category','id');
}
}
上面的关系声明很重要,因为您在控制器的这一行中引用它:
$categories = Category::with('products')->get();
推荐阅读
- c# - 如何将这些名称“插入”到我要更新的方法/变量中?
- c# - 无法加载文件或程序集..即使它在正确的位置并且构建良好
- spring - SpringBoot 创建框架启动库
- r - R - 帮助从 0 构建时间列?
- php - 对特定分类有问题循环
- mysql - 数据库架构:当记录具有不同数量的属性(列)
- python - beautifulsoup select 方法返回回溯
- android - 是什么导致 Google Play 开发者控制台中出现此警告:“我们检测到您的应用正在使用旧版本的 Google Play 开发者 API”
- php - 为什么添加标题后无法获取 POSTFIELDS?
- react-native - 如何在本机反应中跨组件全局调用一种方法