【发布时间】:2017-05-05 06:30:51
【问题描述】:
我的 Laravel 应用程序中有 2 个表,即 customers 和 stores。客户可以属于许多商店,商店可以有很多客户。它们之间有一个数据透视表来存储这种关系。
问题是,如何使用 Eloquent 提取给定商店的客户列表?可能吗?我目前能够使用 Laravel 的 Query Builder 提取它。这是我的代码:
| 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 回答。 -
在旁注中,您的
->withPivot()实际上是错误的,read the docs,您可以在关系本身上定义关系键,即。->belongsToMany(Customer::class, 'customer_store', 'store_id', 'customer_id') -
@Bagus Tesa ...你让我的一天为我工作 belongsToMany(Customer::class, 'customer_store', 'store_id', 'customer_id') ......... ........谢谢..!!
标签: php mysql laravel laravel-5 eloquent