我正在尝试创建类别和产品之间的关系但不知何故我无法使用该类别连接到产品表并打印出产品名称,而是我得到类别的名称
Table Name: products
Columns: id, name, price, category_id, description
Table Name: categories
Columns: id, name, description
id: 1
name: product1
price: 10
category_id: 1
description: p1
---------------
id: 2
name: product2
price: 10
category_id: 1
description: p2
id: 1
name: category1
description: c1
---------------
id: 2
name: category2
description: c2
class Product extends Eloquent
{
protected $product = 'products';
public function category()
{
return $this->belongsTo('Category');
}
}
模型文件夹中的class Category extends Eloquent
{
protected $category = 'categories';
public function product()
{
return $this->hasMany('Product', 'category_id');
}
}
class ProfileController extends BaseController
{
public function user($username)
{
$user = User::where('username', '=', $username);
if ($user->count())
{
$user = $user->first();
$title = 'User Profile';
$category = Category::find(1);
$products = Category::find(1)->name;
return View::make('profile.user', compact('user', 'title', 'category', 'products'));
}
return 'User Not Found. Please Create an Account';
}
}
@extends('layouts.master')
@section('content')
{{ Auth::user()->username }}
<br>
{{ Auth::user()->email }}
<br>
<h1>{{ 'Category name: '. $category->name }}</h1>
<br>
<h3>{{ 'Category Description: ', $category->description }}</h3>
<br>
{{ $products }}
@stop
首先{{$products}}
我使用了foreach循环
@foreach($products as $product)
{{$product}}
@endforeach
然后我收到了这个错误
ErrorException
Invalid argument supplied for foreach() (View: J:\wamp\www\test\app\views\profile\user.blade.php)
所以我尝试了var_dump($products)
并且意识到$products
给出了category1
这个类别的名称,但我想要的是打印所有具有category_id 1的产品的名称
有人可以帮我一把吗?我是否弄乱了这段关系,或者我对代码做了些什么蠢事?
答案 0 :(得分:3)
在您的控制器中:
$category = Category::find(1);
$products = $category->product;
然后在您的模板中,您可以使用:
@foreach ($products as $product)
{{ $product->name }}
@endforeach
更好的是,您可以使用急切加载而忘记手动分配产品:
控制器:
$category = Category::with('product')->where('id', 1)->first();
模板:
@foreach ($category->product as $product)
{{ $product->name }}
@endforeach
PS:在此处阅读更多有关预先加载的内容:http://laravel.com/docs/eloquent#eager-loading 为了防止可怕的N + 1查询问题!