我在我的Laravel应用程序中有两个表,分别是customers和stores。客户可以属于多个商店,商店也可以有多个客户。它们之间有一个中间表来存储这种关系。
问题是,如何使用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->withPivot()
实际上是错误的,请阅读文档,并且你可以在关系本身上定义关系键,例如->belongsToMany(Customer::class, 'customer_store', 'store_id', 'customer_id')
。 - Bagus Tesa