Model Laravel 4多对多关系不起作用,未找到透视表

Model Laravel 4多对多关系不起作用,未找到透视表,model,laravel,many-to-many,laravel-4,eloquent,Model,Laravel,Many To Many,Laravel 4,Eloquent,我目前在与Laravel 4的n:n关系方面遇到问题,我在pivot表上遇到错误,该表查询的两个组件都是单数名称。我创建一个pivot表lands_objs并填充它: 型号为: <?php class Obj extends Eloquent { protected $guarded = array(); public static $rules = array(); public $timestamps = false;

我目前在与Laravel 4的n:n关系方面遇到问题,我在pivot表上遇到错误,该表查询的两个组件都是单数名称。我创建一个pivot表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');
        }
     }
但我认为错误是:

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_obj吗?我错过什么了吗


非常感谢。

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

土地对象而非土地对象

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

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


有关更多信息,请参见

能否告诉我使用2 belongsTo方法和hasManyThrough方法之间的区别?我不明白,但是使用Hasmanytrow对我来说不起作用……考虑到这个场景,一个作者有很多帖子,一个帖子有很多评论。你通常会有2个属于方法(作者到帖子和帖子到评论),但是如果你想为给定的作者选择所有帖子上的所有评论,那么你会使用hasManyThrough,因为这些评论与作者没有直接关系,但它们通过另一个模型(帖子)与作者相关。如果没有hasManyThrough,你必须选择所有作者的帖子,然后循环它们以获取所有评论,然后进行某种处理,使它们符合你所追求的格式/顺序等。
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, ))
return $this->belongsToMany('Obj', 'lands_objs');
return $this->belongsToMany('Land', 'lands_objs');