Laravel 关系有时不起作用

Laravel realtionship sometimes not functional

我有Laravel 5。 bacis e-shop 框架,我尝试使用关系 我有订单,Order_item,产品,客户模型

订单模型与

有关系
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 }}

我的关系还好吗?它是我网店关系的更好解决方案

i post 我的完整代码到 github https://github.com/mardon/MaMushashop

这样做

$order = DB::table('order')
->join('customer', 'order.customer_id', '=', 'customer.id')
->select('order.*', 'customer.*')
->where('order.id', '=', $id)
->first();
$order_items = Order_item::where('order_id', $id)->get();

return view('admin.detail', ['order' => $order, 'order_items' => $order_items]);

并像这样生成项目

@foreach($order_items as $item)
    <tr>
        <th>{{ $item->product->name }}</th>
        <th>{{ $item->quantity }}</th>
        <th>{{ $item->price }}</th>
    </tr>
@endforeach

您的订单商品 table 是 pivot table。订单和产品的关系应声明为 belongsToMany。

  • belongsToMany 用于多对多。
  • hasMany 用于一对多
  • hasOne用于一对一

您的 table Order_item 的命名应该是 order_product 以更好地反映它实际包含的内容。

class order_product extends Model
{
    protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];

    public function product()
    {
        return $this->belongsToMany('App\Product', 'order_product', 'order_id', 'product_id);
    }

    public function order()
    {
        return $this->belongsToMany('App\Order', 'order_product', 'product_id', 'order_id);
    }
}