cap*_*ack 5 php mysql laravel eloquent laravel-5
我的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 |
Run Code Online (Sandbox Code Playgroud)
客户模型:
public function stores(){
return $this->belongsToMany(Store::class)
->withPivot('customer_store', 'store_id')
->withTimestamps();
}
Run Code Online (Sandbox Code Playgroud)
商店型号:
public function customers(){
return $this->belongsToMany(Customer::class)
->withPivot('customer_store', 'customer_id')
->withTimestamps();
}
Run Code Online (Sandbox Code Playgroud)
数据库查询(使用查询生成器):
$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);
Run Code Online (Sandbox Code Playgroud)
Ale*_*Lam 12
试试这个:
public function result(Request $request) {
$storeId = $request->get('storeId');
$customers = Customer::whereHas('stores', function($query) use($storeId) {
$query->where('stores.id', $storeId);
})->get();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7417 次 |
最近记录: |