gpt4 book ai didi

model - Laravel 4多对多关系无法正常工作,找不到数据透视表

转载 作者:行者123 更新时间:2023-12-04 13:33:02 25 4
gpt4 key购买 nike

我目前在与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, ))

尽管对land_obj进行查询,Laravel还是不应该创建表lands_objs吗?我想念什么吗?

非常感谢。

最佳答案

数据透视表应为链接表名称的单数形式,按字母顺序排列,因此在您的情况下:

land_obj而不是lands_objs

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

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


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

有关更多信息,请参见 docs here

关于model - Laravel 4多对多关系无法正常工作,找不到数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16384926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com