【问题标题】:Laravel 4 many to many relationship not working, pivot table not foundLaravel 4多对多关系不起作用,找不到数据透视表
【发布时间】:2013-04-29 09:25:30
【问题描述】:

我目前在与 Laravel 4 的 n: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, ))

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

非常感谢。

【问题讨论】:

    标签: model laravel many-to-many laravel-4 eloquent


    【解决方案1】:

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

    land_obj 而不是lands_objs

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

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

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

    欲了解更多信息,请参阅docs here

    【讨论】:

    • 你能告诉我使用 2 个 belongsTo 方法和 hasManyThrough 方法有什么区别吗?我不明白,但是使用 hasManyTrough 对我不起作用...
    • 假设一个作者有很多帖子,一个帖子有很多评论。您通常有 2 个属于方法(作者发布和发布评论),但是说您想为给定作者选择所有帖子上的所有 cmets,然后您将使用 hasManyThrough 因为 cmets 不是与作者直接相关,但它们通过另一个模型(帖子)与作者相关。如果没有 hasManyThrough,您将不得不选择所有作者的帖子,然后将它们循环获取所有 cmets,然后进行某种处理以使它们成为您所追求的格式/顺序等。
    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 2021-05-31
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多