6

我目前在与 Laravel 4 的 n 关系方面遇到问题,我在透视表时遇到错误,该表正在查询一个表,其中两个组件都是单数名称。我创建了一个数据透视表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');
        }
     }

这是我按照标准填充数据透视表的方法。当然,lands、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');
        });
    }
}

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

$land = Land::find(1);  //checked loads land fine
$objs = $land->objs; //--> HERE 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, ))

尽管查询land_obj,Laravel 不应该创建表lands_objs 吗?我错过了什么吗?

非常感谢。

4

1 回答 1

13

数据透视表应该是它所链接的表名的单数版本,按字母顺序排列,因此在您的情况下:

land_obj 而不是lands_objs

如果您真的不想使用默认命名约定,您还可以将表名指定为模型中 belongsToMany 调用的第二个参数:

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

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

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

于 2013-05-05T15:39:44.633 回答