Laravel 5 Eloquent HasManyThrough - name columns i

2019-08-08 16:10发布

问题:

UPDATE: After looking at the Eloquent hasManyThrough class, without changing it, I cannot see how I could link the tables below. The declarations of params for the method call is:

class HasManyThrough extends Relation
{
    /**
     * The distance parent model instance.
     *
     * @var \Illuminate\Database\Eloquent\Model
     */
    protected $farParent;  // in my case: User::class

    /**
     * The near key on the relationship.
     *
     * @var string
     */
    protected $firstKey;  // in my case: organisation_users_roles(organisation_id)

    /**
     * The far key on the relationship.
     *
     * @var string
     */
    protected $secondKey;  // in my case: users(id)

    /**
     * The local key on the relationship.
     *
     * @var string
     */
    protected $localKey;  // in my case: organisation(id)

So there is no way to tell the standard Eloquent hasManyThrough that first link is organisation(id)->organisation_users_roles(organisation_id) and second link is organisation_users_roles(user_id)->users(id)

Did I misunderstand?


I cannot find an example of the syntax to use if you have three tables linked via hasManyThrough and the column names in each table do not follow the Eloquent naming convention. In my case:

Three tables:

Organisations
Users
Roles
Organisation_Users_Roles (3 way linking)

Because these belong to an already existing app, I cannot change / rename columns.

The linking column names are:

`Organisation: id` links to `Organisation_Users_Roles: organisation_id"
`Users: id` links to `Organisation_Users_Roles: user_id"
`Roles: id` links to `Roles: role_id"

The Organisation_Users_Roles also contains an id column (essentially its primary key or row id).

I have tried (as example) in Organisation class:

public function users()
{
    return $this->hasManyThrough(User::class, OrganisationUserRole::class);
}

In the docs example the tables are:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

So, in the example:

country(id)->users(country_id) and users(id)->posts(user_id)

And in my case:

organisation(id)->organisation_users_roles(organisation_id) and organisation_users_roles(user_id)->users(id)

But since the column names are not exact to the example on Eloquent Docs (as this is a three way linking table) then I get the following error when using the method:

[PDOException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_role_id' in 'on clause'

I want to get the first returned user for the current Organisation, I call it like this:

$entry['created_user_id'] = $organisation->users->first();

Thanks

回答1:

In your organisation table, try

return $this->hasManyThrough('App\..path-to..\User', 'App\..path-to..\Organisation_Users_Roles', 'organisation_id', 'id' );