【发布时间】:2025-06-14 17:15:02
【问题描述】:
我正在使用 larvel 7 创建一个简单的库存系统。我想加入两个表。类别和产品表。 我遇到了问题
****Trying to get property ** '[{"id":1,"product_name":"BoldPen","category":{"id":1,"categoryname":"Pen","created_at":"2021-01-16T16:04:55.000000Z","updated_at":"2021-01-16T16:04:57.000000Z"},"created_at":"2021-01-16T16:06:16.000000Z","updated_at":"2021-01-16T16:06:17.000000Z"},{"id":2,"product_name":"LGTV","category":{"id":3,"categoryname":"Tv","created_at":"2021-01-16T16:05:23.000000Z","updated_at":"2021-01-
of non-object**
我正在创建一个两个表类别,我希望与它们有关系的产品。
分类表
| 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 |
当我运行程序时,我得到的错误是
试图获得财产
我不知道为什么会发生这种情况,请帮我解决问题。到目前为止我尝试了什么,我附在下面。
型号
类别
class Category extends Model
{
use HasFactory;
protected $fillable = [
'categoryname',
];
public function products (){
return $this->hasMany('App\Models\Product','id','category');
}
}
产品
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>
**Routes**
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,
]);
}
}
【问题讨论】:
-
能否请您提供您的类别和产品表的屏幕截图?
-
好的先生............
-
您是否将类别和产品模型保存在 App\Models 目录中?
-
我附上两张表格截图
-
我附上文件夹结构截图方便理解