【发布时间】: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