简体   繁体   English

Laravel 5:如何使用Eloquent对数据透视表进行连接查询?

[英]Laravel 5: How to do a join query on a pivot table using Eloquent?

I have 2 tables in my Laravel application namely customers and stores . 我的Laravel应用程序中有2个表,即客户商店 Customers can belong to many stores and stores can have many customers. 客户可以属于许多商店,商店可以拥有许多客户。 There's a pivot table between them to store that relation. 它们之间有一个数据透视表来存储这种关系。

Question is, how do I extract the list of customers for a given store using Eloquent? 问题是,如何使用Eloquent提取给定商店的客户列表? Is it possible? 可能吗? I am currently able to extract that using Laravel's Query Builder . 我目前能够使用Laravel的Query Builder提取它。 Here is my code: 这是我的代码:

| customers | stores      | customer_store |
-------------------------------------------
| id        | id          | customer_id    |
| name      | name        | store_id       |
| created_at| created_at  | created_at     |
| updated_at| updated_at  | updated_at     |

Customer Model: 客户模型:

public function stores(){
        return $this->belongsToMany(Store::class)
            ->withPivot('customer_store', 'store_id')
            ->withTimestamps();
    }

Store Model: 商店型号:

public function customers(){
        return $this->belongsToMany(Customer::class)
            ->withPivot('customer_store', 'customer_id')
            ->withTimestamps();
    }

DB Query (using Query Builder): 数据库查询(使用查询生成器):

$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);

Try this one: 试试这个:

public function result(Request $request) {

    $storeId = $request->get('storeId');

    $customers = Customer::whereHas('stores', function($query) use($storeId) {
        $query->where('stores.id', $storeId);
    })->get();

}

Try executing this... 尝试执行此...

$result = Customer::with('stores')->get();

Hope this helps. 希望这可以帮助。

To know more about Eloquent Relationship refer: https://laravel.com/docs/5.1/eloquent-relationships 要了解有关Eloquent Relationship的更多信息,请参阅: https//laravel.com/docs/5.1/eloquent-relationships

Try below: 试试以下:

Here Customers is your model and $storeID is your store id. 这里的Customers是您的模型, $storeID是您的商店ID。 $storeID is outside of the scope of your callback. $storeID超出了回调范围。 So you must use the use statement to pass them. 因此,您必须使用use语句来传递它们。

Customers::leftJoin('customer_store', function($join) use($storeID){
  $join->on('customers.id', '=', 'customer_store.customer_id')
  ->where('customer_store.store_id','=', $storeID);
})
->whereNotNull('customer_store.store_id')//Not Null Filter
->get();

Hope this help you! 希望这对你有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM