Laravel:一对多对多,获取与众不同的()值 [英] Laravel: One to Many to Many, retrieve distinct() values

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

问题描述

使用雄辩的ORM的Laravel 4项目.

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 Illuminate\Database\Eloquent\Builder( $query );
    $eloquent->setModel( new Item );
    return $eloquent->get();
}

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

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