Laravel 5 Eloquent HasManyThrough - 链接

时间:2015-12-16 00:09:32

标签: mysql eloquent laravel-5.1

更新:在查看Eloquent hasManyThrough类之后,在不更改它的情况下,我无法看到如何链接下表。方法调用的params声明是:

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)

所以没有办法告诉标准Eloquent hasManyThrough第一个链接是organisation(id)->organisation_users_roles(organisation_id) 第二个链接是organisation_users_roles(user_id)->users(id)

我误解了吗?

如果您通过hasManyThrough链接了三个表,并且每个表中的列名都不遵循Eloquent命名约定,则无法找到要使用的语法示例。就我而言:

三张桌子:

Organisations
Users
Roles
Organisation_Users_Roles (3 way linking)

因为这些属于已有的应用,我无法更改/重命名列。

链接列名称为:

`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"

Organisation_Users_Roles还包含id列(主要是其主键或行ID)。

我在Organisation课程中尝试过(例如)

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

在docs示例中,表格是:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

所以,在例子中:

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

就我而言:

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

但由于列名与Eloquent Docs上的示例不完全相同(因为这是一个三向链接表),因此在使用该方法时出现以下错误:

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

我想获得当前组织的第一个返回用户,我称之为:

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

由于

1 个答案:

答案 0 :(得分:0)

在您的组织表中,尝试

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