Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 5多对多-单数表名_Php_Laravel_Laravel 5 - Fatal编程技术网

Php Laravel 5多对多-单数表名

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 =

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.
    }
}

错误:

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.
    }
}