Teja
Teja

Reputation: 47

Laravel using join get the values from one table and count from another table

I have 3 tables brands, cars, brand_cars now I want to display all the companies and count of the cars in that brand

EX: brand 'a' have total 2 cars, 'b' have 1 car like this

I want to get this by Joins in laravel

Now I am able to get the all brands and count using foreach loop, but I want by using the JOINS

brands
 __________________
| id |   brand    |
|-----------------|
| 10 |    a       |
| 11 |    b       |
| 12 |    c       |
| 13 |    d       |
|-----------------|

cars
 ___________________
| id |     car     |
|------------------|
|  1 |      I1     |
|  2 |      I2     |
|  3 |      I3     |
|  4 |      I4     |
|  5 |      I5     |
|------------------|

brand_cars
 ___________________________
| id |    car   |   brand  |
|--------------------------|
|  1 |     1    |    10    |
|  2 |     2    |    11    |
|  3 |     3    |    12    |
|  4 |     4    |    10    |
|--------------------------|

Thank you in advance.

Upvotes: 1

Views: 1601

Answers (1)

Jeno Karthic
Jeno Karthic

Reputation: 351

If you like to use SQL Joins inside Laravel, you can use Query Builder. http://laravel.com/docs/queries#joins

If you want to use Eloquent ORM, you can use the following.

In Car Model, you need to define, many-to-many with Brand relation. Something like below,

public function brand(){
    return $this->belongsToMany('Brand');  // This will intern use pivot table brand_car for joining.
}

When you want to retrieve particular car's Brand, use as following.

$car = Car::findOrFail(1);  // replace 1 with id.

To print its name and brand in view,

Name: {{$car->car}}, Brand: {{$car->brand->first()->brand}} 

We used first() to retrieve only the first one. Obviously there will be only one in your case.

Upvotes: 1

Related Questions