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

435 Views Asked by At

I use Laravel 7 with Corcel to connect to the database of a WordPress installation.

The connection works fine, no problems fetching data from WordPress so far:
App\Project::where('id',3)->get(); ✔️
App\Tester::where('id',4)->get(); ✔️

In my WordPress installation there are additional tables used by a project management plugin called WP Project Manager. I want to form a many-to-many relationship between a wordpress table (WP: users) and a plugin table (WP-Plugin: pm_projects) via a pivot table (WP-Plugin: pm_role_user).

The plugin's pivot table has four fields: project_id, role_id, assigned_by and user_id. It connects the users with the projects.

So I created the models Project and Tester (in my context a User is regarded to be a Tester) like this:

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');
    }

}

When I try to get a users projects with App\Project::where('id',3)->testers()->get();, I get the following error message:

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

My question:
How can I make many-to-many connections between my WordPress tables in Laravel, using Corcel?

1

There are 1 best solutions below

1
Muhammad Dyas Yaskur On BEST ANSWER

App\Project::where('id',3) is a eloquent query builder instance, not eloquent element. You should use first() method first then your model method/relation. So the code should be like:

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

but it can be simply(and you should use this):

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

It's will return testers collection from project 3.