【发布时间】:2016-10-04 07:59:18
【问题描述】:
我有 Laravel 5. bacis e-shop 框架,我尝试使用关系我有 Order、Order_item、Product、Customer 模型
订单模型与
有关系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
【问题讨论】:
-
让我们take this to chat。这样更容易。
标签: php laravel relationship laravel-5.3