Laravel 4多对多关系不起作用,没有找到数据透视表

Jos*_*oss 6 many-to-many model laravel eloquent laravel-4

我目前在与Laravel 4的关系方面遇到问题,我在使用数据透视表时遇到错误,该表在一个表上查询,其中两个组件都是单数名称.我创建了一个数据透视表lands_objs并填充它:

模型是:

<?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');
        }
     }
Run Code Online (Sandbox Code Playgroud)

以下是我按照标准填充数据透视表的方法.当然存在land,objs和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');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个结构,我应该能够感谢Eloquent:

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

但我接受了错误:

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, ))
Run Code Online (Sandbox Code Playgroud)

即使在land_obj上查询,Laravel也不应该创建表lands_objs吗?我错过了什么吗?

非常感谢.

Bre*_*ent 13

数据透视表应该是它所链接的表名的单数形式,按字母顺序排列,所以在你的情况下:

land_obj而不是lands_objs

如果你真的不想使用默认的命名约定,你还可以指定表名作为您模型中belongsToMany呼叫第二PARAM:

return $this->belongsToMany('Obj', 'lands_objs');
Run Code Online (Sandbox Code Playgroud)

和

return $this->belongsToMany('Land', 'lands_objs');
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此处的文档