Laravel - BelongsToMany 关系忽略我的自定义(单数)table 名称

Laravel - BelongsToMany relation ignores my custom (singular) table name

我正在处理一个较旧的 (laravel 5.6) 代码库,该代码库中有一些模型具有单数 table 名称(不是我设计的..)。当我在 tables "m_sector" 和 "m_tasklist" 之间设置一个新的主元关系时,Eloquent 自动假定 "m_tasklist" 的 table 名称是复数; "m_tasklists"。我知道这是 Laravel 的设计,因此我使用了在任务列表模型中定义的手动覆盖。将 $table 属性 更改为 `protected $table = 'potato' 后;在查询中检测并实施了更改..

错误信息

"debugMessage": "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.m_tasklists' doesn't exist (SQL: select count(*) as aggregate from `m_tasklists` where `id` in (1, 2, 3))"

任务列表模型

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'm_tasklist';

    /**
     * A task list belongs to many sectors.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function sector(): BelongsToMany
    {
        return $this->belongsToMany(Sector::class, 'm_sector_m_tasklist', 'm_tasklist_id', 'm_sector_id');
    }

部门模型

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'm_sector';

    /**
     * A sector belongs to many task lists.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tasklists(): BelongsToMany
    {
        return $this->belongsToMany(Tasklist::class, 'm_sector_m_tasklist', 'm_sector_id', 'm_tasklist_id');
    }

PhpMyAdmin 图片table 姓名

任何人都可以帮我解决这个问题,这已经让我头疼了一天。

如果有人想知道,关键约束已经正确形成,迁移工作正常并且设置正确。如果有帮助,我可以添加它们。

问题不在于模型。我的用例有一个验证规则,它检查项目是否存在于 m_tasklists 而不是 m_tasklist

'rules' => ['exists:m_tasklists,id']

而不是正确的

'rules' => ['exists:m_tasklist,id']

我推荐大家遇到与运行类似的问题

$ php artisan tinker
$ (new Model)->getTable();