【问题标题】:Laravel 5 Eloquent HasManyThrough - name columns in linksLaravel 5 Eloquent HasManyThrough - 链接中的名称列
【发布时间】:2015-12-16 00:09:32
【问题描述】:

更新:查看 Eloquent hasManyThrough 类后,如果不更改它,我看不出如何链接下表。方法调用的参数声明为:

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

在文档示例中,表格是:

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();

谢谢

【问题讨论】:

    标签: mysql eloquent laravel-5.1


    【解决方案1】:

    在您的组织表中,尝试

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

    【讨论】:

    • 嗨巴拉特,它不起作用。我得到users.user_id 未找到。
    • 嗨 Bharat,这返回 null,这是不正确的。查询有效,但其中两个表之间的链接构建不正确(user_role.id = users.id
    猜你喜欢
    • 2014-08-14
    • 2020-03-07
    • 2016-09-24
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2016-09-26
    • 2016-02-11
    相关资源
    最近更新 更多