30

I have a PHP backend that I'm currently changing over to use the Laravel framework. However, I'm not quite sure how the Laravel inner join works.

The SQL query i'm trying to move over to Laravel is:

"SELECT leagues.league_name FROM leagues INNER JOIN countries on leagues.country_id = countries.country_id WHERE countries.country_name = '$country' "

Would someone be able to explain how Laravel Joins work?

Apologies if this question isn't suitable.

1

3 Answers 3

68

It should be something like this (haven't tested):

$leagues = DB::table('leagues')
    ->select('league_name')
    ->join('countries', 'countries.country_id', '=', 'leagues.country_id')
    ->where('countries.country_name', $country)
    ->get();

$leagues will be instance of the Illuminate\Support\Collection object, so you can iterate over it using foreach for example.

You can pass 5th argument to the join() function which will specify type of join (default is "inner").

If you're using Eloquent and have "League" model then you can use join on the model too:

$leagues = League::select('league_name')
    ->join('countries', 'countries.country_id', '=', 'leagues.country_id')
    ->where('countries.country_name', $country)
    ->get();

In this case, $leagues will be an instance of Illuminate\Database\Eloquent\Collection which extends regular Laravel collections and gives you a bit more functionality than regular collections.

However, there is even an easier way to write this without using joins:

$leagues = League::select('league_name')->whereHas('countries', function($query) use ($country) {
    $query->where('country_name', $country);
})->get();

Note that in this example "countries" is not a table name but Eloquent relationship name, so you need to set up your relationships before using this approach.

Also, instead of using join, this example will use two queries, or a nested query, I'm not sure; but something like this: SELECT league_name FROM leagues WHERE country_id IN (SELECT id FROM countries WHERE country_name='$country')

0
14

It's pretty straight-forward, maybe it will make more sense just to see your query using the query builder.

$results = DB::table('leagues')
    ->join('countries', 'leagues.country_id', '=', 'countries.country_id')
    ->where('countries.country_name', $country)
    ->get();
1
  • You have an error here, the table (in join statement) is not "leads" but "leagues" :)
    – Avram
    Jan 16, 2017 at 18:16
3

In Laravel Eloquent you can do this all in very smart way.

parent_table_model::with('relational_table_model')->get();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.