Laravel 4 Many of many relationships do not work, pivot table not found

I am currently having problems with the n: n relationship with Laravel 4, I have an error with a rotation table that queries a table with two components on a singular name. I create a lands_objs pivot table and populate it:

Models:

<?php class Obj extends Eloquent { protected $guarded = array(); public static $rules = array(); public $timestamps = false; public function land() { return $this->belongsToMany('Land'); } <?php class Land extends Eloquent { protected $guarded = array(); public static $rules = array(); public $timestamps = false; public function objs() { return $this->belongsToMany('Obj'); } } 

This is how I fill out the pivot table following the standards. Of course, there are tables land, objs and lands_objs:

 <?php use Illuminate\Database\Migrations\Migration; class CreateLandsObjsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lands_objs', function($table) { $table->integer('land_id'); $table->integer('obj_id'); }); } } 

With this structure, I should be able to do thanks to Eloquent:

 $land = Land::find(1); //checked loads land fine $objs = $land->objs; //--> HERE I TAKE THE ERROR 

But I accept the error:

 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'taylor.land_obj' doesn't exist (SQL: select `objs`.*, `land_obj`.`land_id` as `pivot_land_id`, `land_obj`.`obj_id` as `pivot_obj_id` from `objs` inner join `land_obj` on `objs`.`id` = `land_obj`.`obj_id` where `land_obj`.`land_id` = ?) (Bindings: array ( 0 => 1, )) 

Doesn't Laravel create a lands_objs table despite querying land_obj? Did I miss something?

Thank you very much.

+6
source share
1 answer

The pivot table must be a singular version of the names of the tables it links in alphabetical order, so in your case:

land_obj, not lands_objs

If you really do not want to use the default naming conventions, you can also specify the table name as the second parameter in a call owned by toMany in your models:

 return $this->belongsToMany('Obj', 'lands_objs'); 

and

 return $this->belongsToMany('Land', 'lands_objs'); 

See here for more details.

+13
source

Source: https://habr.com/ru/post/944311/


All Articles