Php Laravel 5多对多-单数表名
MySQL表:Php Laravel 5多对多-单数表名,php,laravel,laravel-5,Php,Laravel,Laravel 5,MySQL表: - category - unit - category_unit (many to many) - category_id - unit_id Laravel 5型: <?php class Unit extends Model { /** * The database table used by the model. * * @var string */ protected $table =
- category
- unit
- category_unit (many to many)
- category_id
- unit_id
Laravel 5型:
<?php
class Unit extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'unit';
}
class Category extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'category';
public function units()
{
return $this->morphToMany('App\Unit', 'category_unit'); // Table not in plural.
}
}
错误:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.category_units' doesn't exist (SQL: select `unit`.*, `category_units`.`category_unit_id` as `pivot_category_unit_id`, `category_units`.`unit_id` as `pivot_unit_id` from `unit` inner join `category_units` on `unit`.`id` = `category_units`.`unit_id` where `category_units`.`category_unit_id` = 1 and `category_units`.`category_unit_type` = App\Category)
Laravel 5试图将表类别单位
作为复数类别单位
。由于我的数据库不是新的,并且已经在生产服务器中使用过,因此无法更改表名
我如何才能将Laravel 5与单数名称一起使用?这里的问题是,您试图使用多态关系创建多对多关系
morptomy()
方法不将表名作为第二个参数。我认为您的情况更简单,只需将关系更改为belongsToMany()
所以你的代码应该是
class Category extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'category';
public function units()
{
return $this->belongsToMany('App\Unit', 'category_unit'); // Table not in plural.
}
}
是否需要使用多态关系?
class Category extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'category';
public function units()
{
return $this->belongsToMany('App\Unit', 'category_unit'); // Table not in plural.
}
}