Level 40
Here is an example of how you can do this, this is standardized for laravel.
Migrations - designations and employee_details
Schema::create('designations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('employee_details', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('designation_id');
$table->timestamps();
$table->foreign('designation_id')
->references('id')
->on('designations')
->onDelete('cascade');
});
Models - relationships one to many
class EmployeeDetail extends Model
{
protected $table = 'employee_details';
public $fillable = [
'designation_id'
];
public function designation() {
return $this->belongsTo(Designation::class);
}
}
class Designation extends Model
{
protected $table = 'designations';
public $fillable = [
'name'
];
public function employee_details() {
return $this->hasMany(EmployeeDetail::class);
}
}
Controller - DesignationController
public function index()
{
return Designation::select('name')->withCount(['employee_details'])->get();
}
// return [ {"name": "Test', "employee_details_count": 2} , ...]