2014-02-16 42 views
1
多態性關係

我的情況是:一個日曆屬於客戶或推銷員Laravel - 機鋒:與命名空間

因爲我也有類,如事件和文件,我用我所有的模型類的命名空間的應用程序\模型。

,所以我成立了多態的關係:

在Calender.php

public function user() { 
    return $this->morphTo(); 
} 
在Customer.php和Salesman.php

public function calendars() { 
    return $this->morphMany('App\Models\Calendar', 'user'); 
} 

現在,當我做

$calendar= Calendar::find(1); //calendar from a salesman 
$calendar->user; //error here 
... 

我得到t他的錯誤消息:

Symfony \ Component \ Debug \ Exception \ FatalErrorException 
Class 'salesman' not found 

我注意到,'salesman'是低套管,也許這是什麼問題?

,這是我從Laravels堆棧跟蹤得到

開:/var/www/cloudcube/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php

// foreign key name by using the name of the relationship function, which 
// when combined with an "_id" should conventionally match the columns. 
if (is_null($foreignKey)) 
{ 
    $foreignKey = snake_case($relation).'_id'; 
} 

$instance = new $related; //HIGHLIGHTED 

在這一行之前,我遇到了類似的錯誤,當時我正在搞亂命名空間,所以我猜這跟它有關。有什麼辦法可以告訴morphTo()方法使用正確的名稱空間嗎?

或者這是別的什麼原因造成這個問題?

也發現了這個解決方案,但似乎無法得到它的工作: Polymorphic Eloquent relationships with namespaces

+0

你可以看到插入數據庫和查詢過程中,記錄您的查詢,看看是在查詢發送。 – Shafiul

+0

問題是查詢沒有被執行,因爲他找不到'顧問'。當我手動(通過覆蓋morphTo())給出命名空間時,該查詢被執行,但使用'App \ Models \ Advisor'來檢查類型值... SUCKS –

回答

5

我發現,爲我工作的解決方案。

我總是在日曆定義與正確的命名空間關係,例如:

public function events() { return $this->hasMany('App\Models\Event'); }

我的問題包括了2併發症:

  1. $calendar->user()morphTo(...)功能不能正常工作因爲我的模型在命名空間中,並且morphTo(...)沒有辦法給這個命名空間。

  2. $salesman->calenders()->get()返回和空單,雖然我的數據庫中的關係都在那裏。我發現這是因爲與查詢綁定。

解決方案1:在日曆編寫自定義morphTo(...)功能覆蓋Laravel的一個。我用Laravels morphTo(...)作爲基地來源。這個函數的最後聲明是return $this->belongsTo($class, $id); 還有$class必須是名稱空間的類名。我使用基本的字符串操作來解決這個問題。

2.的解決方案:在Salesman中寫入自定義morphMany(...)函數,並讓它返回類似於Polymorphic Eloquent relationships with namespaces所述的MyMorphMany(...)

這裏的問題是傳遞給MyMorphMany構造函數的$query具有錯誤的(namespaced)綁定。它將查找where user_type = "App\\Models\\Salesman"

爲了解決這個問題,我在MyMorphMany中使用了一個自定義的getResults()函數,它覆蓋了默認的Laravels實現,我改變了綁定以使用正確的,非命名空間的下殼類名。然後我在MyMorphMany類的get()函數中調用該函數getResults()函數。

我用$query->getBindings()$query->setBindings()來糾正綁定。

希望這樣可以節省別人工作了幾天,像它會救了我:)

+0

您還可以設置'protected $ morphClass ='MyMorphMany'; '作爲一個類變量,因爲那樣你就不需要使用自定義的'getResults()'函數 –

+0

我一直在試圖解決同一個問題,並且仍然停留在這一天。 可以請你分享你修改後的morphto()和morphmany函數嗎? – Yashasvi