Fayakon
Fayakon

Reputation: 1523

why SQL inner join returns empty result in laravel?

can you please check why this code is returning me empty result in laravel. i am trying to fetch nations name based upon nation id in teachers table.

public function edit(Teacher $teacher)
{

  $teachers= DB::table('teachers','nations')
  ->join('nations', 'teachers.nation_id', '=', 'nations.id')
  ->select('teachers.*')
  ->where('teachers.id',$teacher->id)
  ->first();

return view('teachers.create',['teachers' => $teachers]);
}

Upvotes: 0

Views: 1119

Answers (3)

Jithesh Jose
Jithesh Jose

Reputation: 1814

Check this code

public function edit(Teacher $teacher)
{
  $teachers= DB::table('teachers')
    ->join('nations', 'teachers.nation_id', '=', 'nations.id')
    ->select('teachers.*','nations.name')
    ->where('teachers.id','=',$teacher->id)
    ->first();

  return view('teachers.create',['teachers' => $teachers]);
}

Upvotes: 1

Belal mazlom
Belal mazlom

Reputation: 1850

In case you allowed in teachers table for nation_id to be empty value or null, you need to use left join to still have all records from teachers table:

public function edit(Teacher $teacher)
{

  $teachers= DB::table('teachers','nations')
  ->leftJoin('nations', 'teachers.nation_id', '=', 'nations.id')
  ->select('teachers.*', 'nations.name')
  ->where('teachers.id',$teacher->id)
  ->first();
  return view('teachers.create',['teachers' => $teachers]);
}

Upvotes: 1

nakov
nakov

Reputation: 14288

Why do you need to use the query builder to perform such a not complex query?

You can achieve this easier if you add a relationship method in your Teacher model.

So in your Teacher class add the following:

public function nation() {
    return $this->belongsTo(Nation::class);
}

Then in your controller you can use it like this:

$teacher->nation;

Upvotes: 1

Related Questions