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

时间:2016-12-20 05:39:09

标签: php mysql laravel laravel-5 eloquent

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

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

3 个答案:

答案 0 :(得分:10)

试试这个:

public function result(Request $request) {

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

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

}

答案 1 :(得分:2)

尝试执行此操作......

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

希望这有帮助。

要了解有关雄辩关系的更多信息,请参阅:https://laravel.com/docs/5.1/eloquent-relationships

答案 2 :(得分:-1)

尝试以下:

此处Customers是您的模型,$storeID是您的商店ID。 $storeID超出了回调范围。所以你必须使用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();

希望这对你有帮助!