1
MySQL表表名:Laravel 5多對多 - 奇異
- 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以單數名稱使用它?
是否有必要使用多態的關係? –