Laravel 5:如何使用Eloquent在中间表上执行联接查询?

5

我在我的Laravel应用程序中有两个表,分别是customersstores。客户可以属于多个商店,商店也可以有多个客户。它们之间有一个中间表来存储这种关系。

问题是,如何使用Eloquent提取给定商店的客户列表?这是可能的吗?我目前能够使用Laravel的查询构建器来提取。以下是我的代码:

| customers | stores      | customer_store |
-------------------------------------------
| id        | id          | customer_id    |
| name      | name        | store_id       |
| created_at| created_at  | created_at     |
| updated_at| updated_at  | updated_at     |

客户模型:

public function stores(){
        return $this->belongsToMany(Store::class)
            ->withPivot('customer_store', 'store_id')
            ->withTimestamps();
    }

存储数据模型:

public function customers(){
        return $this->belongsToMany(Customer::class)
            ->withPivot('customer_store', 'customer_id')
            ->withTimestamps();
    }

使用查询构建器的数据库查询:

$customer = DB::select(SELECT customers.id, customers.name, customers.phone, customers.email, customers.location FROM customers LEFT JOIN customer_store on customers.id = customer_store.customer_id WHERE customer_store.store_id = $storeID);

澄清一下,DB:select不是一个Query Builder。如果你想获取“Store”的客户,你可以使用$current_store->customers(),这将获取属于该商店的所有客户,前提是$current_store是一个模型实例而不是一个集合。如果您希望检索多个商店并获取它们相关的客户,您可以使用@kapil.dev的答案。 - Bagus Tesa
1
顺便提一下,你的 ->withPivot() 实际上是错误的,请阅读文档,并且你可以在关系本身上定义关系键,例如 ->belongsToMany(Customer::class, 'customer_store', 'store_id', 'customer_id') - Bagus Tesa
@Bagus Tesa...你让我的一天变得美好,它对我起作用了belongsToMany(Customer :: class,'customer_store','store_id','customer_id').......................谢谢..!! - Anmol Mourya
3个回答

14

试试这个:

public function result(Request $request) {

    $storeId = $request->get('storeId');

    $customers = Customer::whereHas('stores', function($query) use($storeId) {
        $query->where('stores.id', $storeId);
    })->get();

}

3
尝试执行以下操作...
$result = Customer::with('stores')->get();

希望这可以帮到您。如果想了解更多关于Eloquent Relationship (Laravel框架的ORM工具) 的信息,请参阅以下链接:https://laravel.com/docs/5.1/eloquent-relationships

我在实现你的代码后遇到了以下错误: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_store.customer_store' in 'field list' (SQL: select stores.*, customer_store.customer_id as pivot_customer_id, customer_store.store_id as pivot_store_id, customer_store.customer_store as pivot_customer_store, customer_store.created_at as pivot_created_at, customer_store.updated_at as pivot_updated_at from stores inner join customer_store on stores.id = customer_store.store_id where customer_store.customer_id in (1, 2, 3)) - captainblack
1
显然,看看我的评论,在你的帖子上。然而,->with() 假定你正在加载一个 Customers 集合。 - Bagus Tesa
准确!! @captainblack 你应该参考BagusTesa的评论,他解释得很好。 - kapilpatwa93
2
@kapil.dev 你在哪里传递 'store_id'? - Anish688
@Anish688 应该将其映射到数据透视表中,它将提供属于该客户的映射商店...如果概念仍然不清楚,请阅读文档。 - kapilpatwa93

1

请尝试以下:

这里的Customers是您的模型,$storeID是您的店铺ID。$storeID在回调范围之外,因此您必须使用use语句来传递它们。

Customers::leftJoin('customer_store', function($join) use($storeID){
  $join->on('customers.id', '=', 'customer_store.customer_id')
  ->where('customer_store.store_id','=', $storeID);
})
->whereNotNull('customer_store.store_id')//Not Null Filter
->get();

希望这能帮到您!

3
这不是有点过于复杂了吗?OP希望以尽可能流畅的方式表达“如何使用Eloquent提取给定商店的客户列表?” 也许阐述为什么给出这个答案会更好。 - Bagus Tesa
嘿,@AddWeb,你的代码有点可行,但它也返回了所有顾客(不属于该店铺的顾客)。 - captainblack
是的,基于OP的DB查询(使用查询构建器)点。我尝试使用高级联接给出最佳解决方案。 - AddWeb Solution Pvt Ltd
这是随您的代码返回的额外客户信息: { "id": 3, "name": "User 3", "phone": "102", "email": "u3@x.com", "location": "WA", "created_at": null, "updated_at": null, "customer_id": null, "store_id": null } - captainblack
1
这个可以工作,但是我觉得解决方案应该像Eloquent查询一样易于阅读。 - captainblack
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接