我有Laravel 5. bacis电子商店的框架,我尝试使用我有Order,Order_item,Product,Customer model的关系
订单模型具有关联性
class Order extends Model
{
protected $fillable = ['user_id', 'status'];
protected $dates = ['created_at'];
/**
* Get the items for the order.
*/
public function items()
{
return $this->hasMany('App\Order_item');
}
public function customer()
{
return $this->hasOne('App\Customer','id');
}
}
订单商品
class Order_item extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function product()
{
return $this->hasOne('App\Product','id');
}
}
在控制器中
public function detail($id)
{
$order = Order::with('customer','items')->findOrFail($id);
return view('admin.detail', ['order' => $order]);
}
而且我认为
<h2>Objednávka č. {{ $order->id }}</h2>
<h3>Zákazník:</h3>
{{ $order->customer->firstname }} {{ $order->customer->lastname }}
<p>{{ $order->customer->email }}</p>
{{ $order->customer->phone }}
<h3>Adresa:</h3>
<p>{{ $order->customer->street }}</p>
<p>{{ $order->customer->city }}</p>
<p>{{ $order->customer->psc }}</p>
<h3>Položky:</h3>
<table class="table table-bordered table-striped">
<thead>
<th>Název</th>
<th>Počet</th>
<th>Cena</th>
</thead>
<tbody>
@foreach($order->items as $item)
<tr>
<th>{{ $item->product->name }}</th>
<th>{{ $item->quantity }}</th>
<th>{{ $item->price }}</th>
</tr>
@endforeach
</tbody>
</table>
现在当我测试某个订单的代码是功能但是对于某些人没有,问题出在{{$ item-> product-> name}}
我的关系好吗?它是我电子商店关系的更好解决方案
我将我的完整代码发布到github https://github.com/mardon/MaMushashop
2 回答
您的订单商品表是pivot table . 对于订单和产品的关系应该声明为belongsToMany .
belongsToMany 用于多对多 .
hasMany 用于One To Many
hasOne 用于一对一
您的表Order_item的命名应该是order_product,以更好地反映它实际包含的内容 .
这样做
并生成这样的项目