Laravel:一对多对多,检索 distinct() 值 [英] Laravel: One to Many to Many, retrieve distinct() values

查看:45
本文介绍了Laravel:一对多对多,检索 distinct() 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel 4 项目,使用 Eloquent ORM.

Laravel 4 Project, using Eloquent ORM.

我有三个表:客户、订单和产品(+ 1 个数据透视表 order_product).客户与订单一对多关联.订单与产品多对多关联.

I have three tables: customers, orders and products (+ 1 pivot table order_product). Customers are linked one-to-many to Orders. Orders are linked many-to-many to Products.

Customers  1-->N  Orders  N<-->N   Products

我想在 Customer 模型上有一个方法来检索客户正在购买的产品列表.

I would like to have a method on Customer model that retrieves a list of products that customer is buying.

为了更好地理解这一点,假设产品是消耗品.

To better understand this, assume products are consumable.

例如,客户 #1 可以放置:

For example Customer #1 can place:

  • 产品 A、B 和 C 的订单 #1;
  • 产品 A、C 和 D 的订单 #2;
  • 产品 C 和 E 的订单 #3;

...我要检索的结果是包含产品 A、B、C、D 和 E 的集合.

...and the result I want to retrieve is a Collection with Products A, B, C, D and E.

模型是(动态伪编码):

Models are (pseudo-coded on the fly):

class Product extends Eloquent {

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

}

class Orders extends Eloquent {

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

    public function products()
    {
        return $this->belongsToMany('Product');
    }

}

class Customers extends Eloquent {

    public function orders()
    {
        return $this->hasMany('Orders', 'customer_id');
    }

    public function products()
    {
        // What to put here ???
    }

}

推荐答案

感谢@deczo 的回答,我能够提出一个单一的查询方法来检索项目:

Thanks to @deczo's answer, I was able to put up a single query method to retrieve items:

public function items()
{
    $query = DB::table('items')->select('items.*')
        ->join('item_order', 'item_order.component_id', '=', 'items.id')
        ->leftJoin('orders', 'item_order.order_id', '=', 'orders.id')
        ->leftJoin('customers', 'customers.id' , '=', 'orders.customer_id')
        ->where('customers.id', $this->id)
        ->distinct()
        ->orderBy('items.id');

    $eloquent = new IlluminateDatabaseEloquentBuilder( $query );
    $eloquent->setModel( new Item );
    return $eloquent->get();
}

这篇关于Laravel:一对多对多,检索 distinct() 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆