I'm currently having problems with a n:n relationship with Laravel 4, I'm having an error wiht pivot table which is quering on a table with with both components on singular name. I create a pivot table lands_objs and populate it:
Models are:
<?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');
}
}
Here is how I populate the pivot table following the standards. Of course lands, objs and lands_objs tables exist:
<?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 take 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, ))
Shouldn't Laravel create the table lands_objs in spite of quering on land_obj? Am I missing something?
Thanks a lot.
The pivot table should be singular version of the table names it is linking, in alphabetical order so in your case:
land_obj rather than lands_objs
If you really don't want to use the default naming conventions you can also specify the table name as the 2nd param on the belongsToMany call in your models:
return $this->belongsToMany('Obj', 'lands_objs');
and
return $this->belongsToMany('Land', 'lands_objs');
For more information see docs here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With