【问题标题】:Laravel Eloquent for sale-product-customer relationshipLaravel Eloquent 用于销售-产品-客户关系
【发布时间】:2013-12-07 16:01:00
【问题描述】:

所以使用 Laravel 4,我有一个 Sales 表,它与 Products 表具有多对多关系,并且它也有与 Customers 表的一对多关系。

我的模型设置如下:

class Sale extends Eloquent {
...
    public function products(){
        return $this->belongsToMany('Product');
    }
    public function customers(){
        return $this->belongsTo('Customer');
    }
}

class Product extends Eloquent {
...
    public function sales(){
        return $this->belongsToMany('Sale');
    }
}

class Customer extends Eloquent {
...
    public function sales(){
    return $this->hasMany('Sale');
    }
}

我要做的是返回所有销售的数据,包括每个销售中包含的每个产品的数据和购买它的客户的数据。

在我的 SalesController 中,我使用即时加载来查询我的数据,如下所示:

public function index()
{
    return Sale::with('products', 'customers')->get();
}

它返回一个包含销售数据、产品数据的对象,但客户数据为空。

如何使用 Eloquent(或自定义查询)来实现这一点?

编辑

这是它返回的对象字符串:

[{"id":1,"customer_id":1,"date":"2013-11-21","status":1,"created_at":"0000-00-00 00:00:00","updated_at":"0000-00-00 00:00:00","products":[{"id":1,"name":"Monitor","price":50,"status":1,"created_at":"0000-00-00 00:00:00","updated_at":"0000-00-00 00:00:00","pivot":{"sale_id":1,"product_id":1,"custom_price":25,"order":1}}],"customers":null}]

【问题讨论】:

  • 我看到你做对了。我认为问题出在其他地方。
  • 我对你的代码有点困惑。在销售模式中,不应该是customer单数来表示1:n的关系吗?
  • 我们能看到数据定义吗? sales 表是否有 customer_id 字段?
  • @J.T.Grimes:我的 Sales 表有:id, customer_id, date, status Customer 有基本的客户数据,Product 有基本的产品数据。
  • @ManuelPedrera 我把它改成了单数,它起作用了!惊人的!!您可以将您的评论作为答案,以便我接受它是正确的吗??

标签: php laravel laravel-4 eloquent eager-loading


【解决方案1】:

尝试将您的 customers 关系更改为单数:

class Sale extends Eloquent {
...
    public function products(){
        return $this->belongsToMany('Product');
    }
    public function customer(){ // <- here
        return $this->belongsTo('Customer');
    }
}

(从 cmets 转移到答案)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2022-11-11
    • 2020-10-31
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多