【发布时间】:2015-11-22 01:20:04
【问题描述】:
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 = '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.
}
}
控制器代码:
$category = Category::find($id);
var_dump($category->units);
错误:
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 正在尝试查找表 category_unit 作为复数 category_units。由于我的数据库不是新数据库,而且我已经在生产服务器中使用过它,因此我无法更改表名。
如何让 Laravel 5 使用单数名称?
【问题讨论】:
-
是否需要使用多态关系?