Corcel :如何在 Laravel 中的 WordPress 表之间形成多对多关系?

Corcel : How to form a many-to-many relationship between WordPress tables in Laravel?

我使用 Laravel 7Corcel 连接到 的数据库WordPress 安装.

连接正常,到目前为止从 WordPress 获取数据没有问题:
App\Project::where('id',3)->get();✔️
App\Tester::where('id',4)->get();✔️

在我的 WordPress 安装中,有一个名为 WP Project Manager 的项目管理插件使用了额外的 table。我想在 wordpress table (WP: users) 和插件 table (WP-Plugin: pm_projects) 通过枢轴 table (WP-Plugin: pm_role_user).

插件的pivot table有四个字段:project_id, role_id, assigned_byuser_id。它将用户与项目联系起来。

所以我创建了模型 ProjectTester(在我的上下文中,用户被视为测试人员),如下所示:

Project.php

<?php

namespace App;

use Corcel\Model as Model;

class Project extends Model
{

    protected $table = 'pm_projects';

    protected $fillable = [
        'title',
        'description',
        'status',
        'budget',
        'pay_rate',
        'est_completion_date',
        'color_code',
        'order',
        'projectable_type',
        'completed_at',
        'created_by',
        'updated_by',
    ];

    protected $dates = [
        'est_completion_date'
    ];

    public function testers()
    {
        return $this->belongsToMany(Tester::class, 'pm_role_project_users', 'role_project_id', 'user_id');
    }

}

Tester.php

<?php

namespace App;

use Corcel\Model\User as User;

class Tester extends User
{

    public function projects()
    {
        return $this->belongsToMany(Project::class, 'pm_role_project_users', 'user_id', 'role_project_id');
    }

}

当我尝试使用 App\Project::where('id',3)->testers()->get(); 获取用户项目时,我收到以下错误消息:

BadMethodCallException with message 'Call to undefined method Illuminate/Database/Eloquent/Builder::testers()'

我的问题:
如何使用 Corcel 在 Laravel 中的 WordPress table 之间建立多对多连接?

App\Project::where('id',3) 是一个 eloquent 查询生成器实例,而不是 eloquent 元素。您应该先使用 first() 方法,然后再使用您的模型 method/relation。所以代码应该是这样的:

App\Project::where('id',3)->first()->testers()->get();

但它可以很简单(你应该使用它):

App\Project::where('id',3)->first()->testers;

这是来自项目 3 的 return 测试人员集合。