【发布时间】:2016-07-30 17:29:32
【问题描述】:
在我的项目中,我有很多产品的订单和有很多订单的客户。我很困惑,因为我想获得某个客户的所有订单以及每个订单的产品。我在某个地方搞砸了一些事情,我不确定我是否正确设置了我的关系。这是我的产品表:
这是我的客户表:
这是我的订单表:
这是我的模型:
产品:
class Product extends Model
{
public function orders()
{
return $this->belongsToMany('App\Order');
}
}
订单:
class Order extends Model
{
public function products()
{
return $this->hasMany('App\Product', 'id');
}
public function customer()
{
return $this->belongsTo('App\Customer');
}
}
客户:
class Customer extends Model
{
public function orders()
{
return $this->hasMany('App\Order', 'id');
}
}
我在我的 CustomersController 中使用 App\Customer::all() 从我的数据库中获取所有客户,并在我的 customers.blade.php 中传递数据。
<h1>Customers:</h1>
@foreach($customers as $customer)
<h3>{{$customer->name}}</h3>
@foreach($customer->orders as $order)
<p>Order ID: {{$order->id}}</p>
@foreach($order->products as $product)
<p>Product title: {{$product->title}}</p>
@endforeach
@endforeach
<hr>
@endforeach
这是输出:
如果有人能解释为什么它没有输出所有内容并给出一些建议,如果这是处理关系的方式,我将非常感激。
【问题讨论】:
-
尝试将 {{ }} 更改为 {!! !!}
-
为了模型更改
return $this->hasMany('App\Product', 'id');到return $this->hasMany('App\Product');
标签: php mysql laravel eloquent blade