[英]CakePHP: associating two models using different databases?
我有兩個模型,Plant和Emp,它們具有Has And Belongs To Many關系。 我已經將它們配置為關聯,並且獲取每個數據的查詢是正確的,但問題是Plant和Emp在不同的數據庫上。 Emp位於數據庫1上,Plant位於數據庫2上。因此,它們不會正確查詢連接表; 連接表僅在數據庫1上。
當Plant模型嘗試訪問連接表時,它將查詢沒有此數據的數據庫2。
這是Emp為Plant提供的協會。
var $hasAndBelongsToMany = array(
'Plant' =>
array(
'className' => 'Plant',
'joinTable' => 'emp_plant',
'foreignKey' => 'employee_id',
'associationForeignKey' => 'LocationID',
'unique' => true,
'conditions' => '',
)
);
更新 :我試圖設置一個“finderQuery”屬性讓我查詢連接表,但我不知道如何給出這樣的原始SQL查詢,並允許它動態地使用模型實例的id而不是預定義的值。
我可以設置類似的東西
SELECT * FROM [Plant] AS [Plant] JOIN [DB].[DBO].[empplant] AS
[EmpPlant] ON ([EmpPlant].[employee_id] = **4**
AND [EmpPlant].[ID] = [Plant].[LocationID])
這將為我提供一個員工的正確數據,但我不知道如何使這個finderQuery成為動態查詢。 必須有一種方法可以實現這一點。
嘗試
var $useDbConfig = 'alternate';
在您的模型類中。
我需要使用自定義finderQuery
並使用特殊的{$__cakeID__$}
標識符代替匹配的模型ID。 這是上面示例的固定版本,在$hasAndBelongsToMany
數組的關系條目中設置為finder查詢。
'finderQuery'=>'SELECT * FROM [Plant] AS [Plant] JOIN [DB].[DBO].[empplant] AS
[EmpPlant] ON ([EmpPlant].[employee_id] = {$__cakeID__$}
AND [EmpPlant].[ID] = [Plant].[LocationID])'
這有效,但如果有人知道如何修復這種情況沒有自定義查找器查詢(我試圖通過使用關聯避免),請發布一個答案,我將標記為正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.