Laravel 4 多对多关系不起作用,找不到数据透视表 [英] Laravel 4 many to many relationship not working, pivot table not found

查看:20
本文介绍了Laravel 4 多对多关系不起作用,找不到数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

模型是:

<?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表是存在的:

Here is how I populate the pivot table following the standards. Of course lands, objs and lands_objs tables exist:

<?php

use IlluminateDatabaseMigrationsMigration;

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:

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

但我接受错误:

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, ))

Laravel 不应该在查询land_obj 的情况下创建表lands_objs 吗?我错过了什么吗?

Shouldn't Laravel create the table lands_objs in spite of quering on land_obj? Am I missing something?

非常感谢.

推荐答案

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

The pivot table should be singular version of the table names it is linking, in alphabetical order so in your case:

land_obj 而不是lands_objs

land_obj rather than lands_objs

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

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');

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

有关详细信息,请参阅此处的文档

这篇关于Laravel 4 多对多关系不起作用,找不到数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆