【发布时间】:2021-12-21 07:27:21
【问题描述】:
我正在使用 Laravel 8 创建一个简单的库存系统。
我想加入两个表:category 和 products
分类表:
| id | categoryname |
|---|---|
| 1 | drink |
| 2 | biscuits |
| 3 | toy |
产品表:
| id | prodname | catid |
|---|---|---|
| 1 | fanta | 1 |
| 2 | apple juice | 1 |
| 3 | buildblocks | 3 |
我需要将数据作为以下输出传递给表格
| id | productname | categoryname |
|---|---|---|
| 1 | fanta | drink |
运行程序时出现以下错误:
未定义属性:App\Models\Product::$category
类别
class Category extends Model
{
protected $fillable = [
'id',
'catname',
];
public function products()
{
return $this->hasMany('App\Models\Product', 'id', 'catid');
}
}
产品
class Product extends Model
{
protected $fillable = [
'id',
'prodname',
'catid',
];
public function category()
{
return $this->belongsTo('App\Models\Category', 'category', 'id');
}
}
view.blade.php
<html>
<head>
<body>
<tbody>
@foreach ($products as $key => $product)
<tr>
<td>{{ $key }}</td>
<td>{{ $product->prodname }}</td>
<td>{{ $product->category->catname }}</td>
</tr>
@endforeach
</tbody>
</body>
</head>
</html>
控制器
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function view()
{
$products = Product::with('category')->get();
$categories = Category::with('product')->get();
return view('product.view')-> with([
'products' => $products,
'categories' => $categories,
]);
}
}
路线
Route::get('/products', [ProductController::class, 'view']);
【问题讨论】:
-
products表中的外键是
catid还是category? -
是产品表中的外键 catid
-
我在上面添加数据库表