1

I want to retrieve data from Model employee.php by laravel eloquent relationship features. But I could't do it.

Model : Employee.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $table = 'employees';
    protected $fillable = [
        'name','fatname','designation_id','rank','office_id','join_date','phone','address','active',
    ];

    protected $primaryKey = 'id';
    public $timestamps = false;

    public function designation(){
        return $this->belongsTo(Designation::class, 'designation_id');
    }

    public function office(){
        return $this->belongsTo(Office::class, 'office_id');
    }

}

EmployeeController.php

<?php

namespace App\Http\Controllers\API;

use App\Employee;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class EmployeeController extends Controller
{
    public function index()
    {
        //Joing Query
        return DB::table('employees')
            ->join('designations', 'employees.designation_id', '=', 'designations.id')
            ->join('offices', 'employees.office_id', '=', 'offices.id')
            ->select('employees.*', 'designations.name', 'designations.seniority', 'offices.name')
            ->orderBy('designations.seniority', 'asc')
            ->get();


        //Alternative Way
        //Eloquent Relationship
        // offices and designation two table 
        return Employee::with(['office', 'designation'])
                        ->where('active', 1)
                        ->orderby('designation.seniority', 'asc')
                        ->get();
    }

But the Eloquent Relationship is not working here orderby designation field. How can I solve it?

iamab.in
  • 2,022
  • 3
  • 18
  • 39
Ruhul
  • 71
  • 2
  • 10
  • check here https://stackoverflow.com/questions/25700529/laravel-eloquent-how-to-order-results-of-related-models – Abhin K Mar 19 '20 at 06:40
  • I have tried like this way but orderby not working return Employee::with(['office','designation' => function ($q) { $q->orderBy('seniority', 'asc'); }])->where('active', 1)->get(); – Ruhul Mar 23 '20 at 05:29
  • There is an alternate method. you can use collection sorting. Employee::with(['office', 'designation']) ->where('active', 1) ->sortBy(function ($item){ return $item->designation->seniority; }); – Abhin K Mar 23 '20 at 08:10

0 Answers0