【问题标题】:Laravel 5 Many to Many - Table name in singularLaravel 5 多对多 - 单数表名
【发布时间】: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 使用单数名称?

【问题讨论】:

  • 是否需要使用多态关系?

标签: php laravel laravel-5


【解决方案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.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-20
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多