我的Laravel应用程序中有2个表,即客户和商店.客户可以属于许多商店,商店可以拥有许多客户.它们之间有一个数据透视表来存储这种关系.
问题是,如何使用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);
解决方法
试试这个:
public function result(Request $request) { $storeId = $request->get('storeId'); $customers = Customer::whereHas('stores',function($query) use($storeId) { $query->where('stores.id',$storeId); })->get(); }