gpt4 book ai didi

php - 拉维尔 5 : How to do a join query on a pivot table using Eloquent?

转载 作者:可可西里 更新时间:2023-11-01 07:12:25 25 4
gpt4 key购买 nike

我的 Laravel 应用程序中有 2 个表,即 customersstores。客户可以属于许多商店,而商店可以有很多客户。它们之间有一个数据透视表来存储该关系。

问题是,如何使用 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();

}

关于php - 拉维尔 5 : How to do a join query on a pivot table using Eloquent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com