简体   繁体   English

雄辩的多对多

[英]Eloquent many-to-many

Using Laravel, I'm having some trouble accessing my other tables, which are all many to many. 使用Laravel,我在访问其他很多表时遇到了一些麻烦。

在此处输入图片说明

So basically, I start out with the user id and want to list the customers that user has. 因此,基本上,我从用户ID开始,想列出该用户拥有的客户。

public function customers()
{
    return $this->belongsToMany('Customer', 'user_to_customer');
}

This works, assume my user id is 1: 假设我的用户ID为1:

User::find(1)->customers;

However now I want to say, for each of these customers, list their products. 但是现在我要说的是,对于这些客户中的每一个,列出他们的产品。 However this needs to be within the same result. 但是,这必须在相同的结果之内。

I guess I would need something within the Customer model, such as: 我想我在客户模型中需要一些东西,例如:

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

I can't seem to work out how to access this within the same query? 我似乎无法解决如何在同一查询中访问此内容? Something like: 就像是:

User::find(1)->customers->products;

Not sure.. any suggestions? 不知道..有什么建议吗?

You can look into eager loading to accomplish this behavior. 您可以调查急切的加载以完成此行为。 Given the following model relationships: 给定以下模型关系:

class User extends Eloquent {

    public function customers()
    {
        return $this->has_many( 'Customer' );
    }

}

class Customer extends Eloquent {

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

}

class Product extends Eloquent {}

The following query will return all products belonging to customers belonging to a specific (in this case, first) user: 以下查询将返回属于特定用户(在这种情况下为第一用户)的客户的所有产品:

User::with(array('customers', 'customers.products'))->first();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM