【问题标题】:Laravel 4 eloquentLaravel 4 雄辩
【发布时间】:2014-03-18 12:32:58
【问题描述】:

有什么方法可以用 eloquent 做到这一点吗?

$orders = Customer::with('orders','orders.shop')->where('orders.shop.location','=','Japan')->get()

Customers、orders 和 shop 是一个表,其中 1 个客户有很多订单,每个订单只有一个商店。

位置是商店表中的一列

我不断收到一条错误消息,指出 orders.shop.location 是一个未找到的列。

有人可以帮忙吗?提前致谢。

【问题讨论】:

  • 您是否在模型中设置了关系?

标签: laravel-4 eloquent


【解决方案1】:

您需要在模型类中定义关系。

客户模型:

public function orders()
{
    return $this->hasMany('Order');
}

订购型号:

public function customer()
{
    return $this->belongsTo('Customer');
}

那么,如果您想要特殊客户的订单,您只需要这样做:

$orders = Customer::find($id)->orders;

或查找附加到订单的用户:

$user = Order::find($id)->user;

您还可以在 Shop 和 Order 模型之间使用相同类型的关系,并执行以下操作:

$orders = Order::with(array('shop' => function($query)
{
    $query->where('location', '=', 'japan');

}))->get();

这应该为您提供位于日本的商店的所有订单。

有关此类请求的更多信息: http://laravel.com/docs/eloquent#eager-loading

【讨论】:

    【解决方案2】:

    在 CostumerModel 中您需要设置关系(一对多):

    public function order()
    {
        return $this->hasMany('OrderModel', 'foreign_key_in_orderTable');
    }
    

    也在 OrderModel 中:

    public function costumer()
    {
        return $this->belongsTo('CostumerModel', 'foreign_key_in_orderTable');
    }
    

    然后在 OrderModel 中与 Shop 建立另一种关系(一对一):

    public function shop()
    {
        return $this->hasOne('ShopModel', 'foreign_key');
    }
    

    现在在 ShopModel 中(一对一):

    public function order()
    {
        return $this->belongsTo('OrderModel', 'local_key');
    }
    

    查询:

    $orders = Customer::with('costumer', 'shop')->where('location','=','Japan')->get();
    

    【讨论】:

      猜你喜欢
      • 2013-09-09
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2013-06-04
      相关资源
      最近更新 更多