2015-12-16 35 views
1

更新:在查看雄辯hasManyThrough類,沒有改變它,我看不到我怎麼可以鏈接下面的表。 PARAMS方法調用的聲明是:Laravel 5雄辯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) 

所以沒有辦法告訴標準雄辯hasManyThrough即第一環節是organisation(id)->organisation_users_roles(organisation_id) 和第二鏈路organisation_users_roles(user_id)->users(id)

我誤解?


我找不到語法的例子,如果你有通過hasManyThrough連接三個表和每個表中的列名不遵循雄辯命名約定使用。在我的情況:

三個表:

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)

但由於列名不準確就洋洋灑灑文檔的例子(因爲這是一個三對向鏈接表),那麼我會收到以下錯誤使用該方法時:

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

我想返回的第一個用戶當前組織,我這樣稱呼它:

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

感謝

回答

0

在您的組織表,嘗試

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

嗨巴拉特,這是行不通的。我找不到'users.user_id'。 – TheRealPapa

+0

請參閱我編輯的答案 –

+0

嗨Bharat,這將返回null,這是不正確的。查詢可以正常工作,但兩個表之間的鏈接不正確地構建('user_role'.'id' ='users'.'id')) – TheRealPapa