首页 > 解决方案 > 在 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,
    ]);
    }

}

在此处输入图像描述

标签: phplaravellaravel-7

解决方案


在您的类别模型中,您还必须添加反向关系,因为您在要检索类别列表时使用它。

类别型号:

class Category extends Model
{
    protected $fillable = [
        'categoryname',
    ];

    public function products (){
        return $this->hasMany('App\Models\Product','category','id');
    }
}

上面的关系声明很重要,因为您在控制器的这一行中引用它:

$categories = Category::with('products')->get();

推荐阅读