2015-11-21 75 views
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以單數名稱使用它?

+0

是否有必要使用多態的關係? –

回答

1

這裏的問題是,你正在嘗試使用多態一個創建多對多關係。

morphToMany()方法不會將表名稱作爲第二個參數。我覺得你的情況比較簡單,只需要改變的關係,以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. 
    } 
}