【发布时间】:2014-04-08 19:16:12
【问题描述】:
我正在尝试在类别和产品之间创建关系,但不知何故我无法使用类别连接到产品表并打印出产品名称,而是获得了类别的名称
在我的数据库中
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
models文件夹内的Product.php
class Product extends Eloquent
{
protected $product = 'products';
public function category()
{
return $this->belongsTo('Category');
}
}
models文件夹中的Category.php
class Category extends Eloquent
{
protected $category = 'categories';
public function product()
{
return $this->hasMany('Product', 'category_id');
}
}
控制器文件夹中的 ProfileController.php
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';
}
}
user.blade.php 在 profile 文件夹中,在 view 文件夹中
@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 的产品的名称
有人可以帮我解决这个问题吗?是我搞砸了关系还是我对代码做了一些愚蠢的事情?
【问题讨论】:
-
您的类别是否可以包含多个产品,您的一个产品是否可以包含多个类别?
-
这部分对我来说没有意义:$category = Category::find(1); $products = Category::find(1)->name;不应该是 $products = $category->product; ?请在一对多关系上使用复数 btw(产品)
-
kevin> 我以为我在需要的地方使用了复数,我错过了什么吗?请你指出来,以便我改变它。谢谢^_^
-
您的产品关系基于 hasMany 设计。 $category->product 在一个类别很可能有多个产品的情况下没有意义,使用复数可以让以后更容易理解(所以 $category->products 在你的情况下)
标签: php mysql database laravel foreign-key-relationship