Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

davidvera's avatar

Convert SQL to Eloquent

Hello, I created 3 tables : langs, sectors and lang_sector (as pivot table)...

the sectors table contains :

$table->increments('id');

The langs table contains :

$table->increments('id');
$table->string('name', 80)->nullable();

And the pivot table :

$table->integer('lang_id');
$table->integer('sector_id')->index('FK_SECTORS');
$table->string('name', 80)->nullable();
$table->string('shortname', 40)->nullable();
$table->text('description', 65535)->nullable();
$table->primary(['lang_id','sector_id']);  

I created 2 models lang & sector and include the relations : Sector model

public function langs(){
    return $this->belongsToMany('App\Lang')->withPivot('name','shortname','description');
}

Lang model

public function sectors(){
    return $this->belongsToMany('App\Sector')->withPivot('name','shortname','description');
}

I have a SQL request :

SELECT DISTINCT
      sectors.id,
      lang_sector.sector_id,
      lang_sector.lang_id,
      lang_sector.admin_id,
      langs.name,
      lang_sector.name,
      lang_sector.shortname,
      admins.name,
      admins.surname,
      sectors.created_at,
      sectors.updated_at
FROM lang_sector
INNER JOIN
      langs ON langs.id = lang_sector.lang_id
INNER JOIN
      sectors ON sectors.id = lang_sectors.sector_id
INNER JOIN
      admins ON admins.id = lang_sector.admin_id
ORDER BY lang_sector.sector_id;

I prepare a crud on which i'd like to see all entries of my table... I would like to use Eloquent to display my results...

0 likes
0 replies

Please or to participate in this conversation.