lundi 19 décembre 2016

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. 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? Is it possible? I am currently able to extract that using Laravel's 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);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire