我不得不改变我的整个职位,因为我认为我不能明确自己。另外,我有一个答案,但我相信这是因为我对这个问题的解释很差,所以这个答案对我的情况没有多大帮助。
请允许我更清楚地解释。以下是我的模型:
class HomeLoanDistributionsDetail extends AppModel {
var $name = 'HomeLoanDistributionsDetail';
var $actsAs = array('Logable' => array(
'userModel' => 'User',
'userKey' => 'user_id',
'change' => 'list', // options are 'list' or 'full'
'description_ids' => TRUE // options are TRUE or FALSE
));
var $validate = array(
'entry_date' => array(
'rule' => 'date',
'message' => 'Enter a valid date',
'allowEmpty' => true
),
'branch_id' => array('numeric'),
'customer_id' => array('numeric'),
'loan_amount' => array('numeric'),
'service_charge' => array('numeric'),
'security' => array('numeric'),
'loan_taken_term' => array('numeric'),
'purpose_id' => array('numeric'),
'installment_amount' => array('numeric'),
'installment_service_charge' => array('numeric'),
);
//The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Customer' => array(
'className' => 'Customer',
'foreignKey' => 'customer_id',
'fields' => 'id,name,fathers_or_husbands_name,credit_card_no,membership_type'
),
'Branch' => array(
'className' => 'Branch',
'foreignKey' => 'branch_id',
'fields' => 'id,name',
),
'HomeLoanCategory' => array(
'className' => 'HomeLoanCategory',
'foreignKey' => 'category_id',
'fields' => 'id,name',
)
);
我还有另外两个模型类:
LoanGroup
loan_groups
LoanGroupsCustomer
loan_groups_customers
最重要的一点是:
LoanGroupsCustomer
有一个名为customer_id
的字段LoanGroupsCustomer
有另一个名为loan_group_id
的字段,它是LoanGroup
的外键。LoanGroup
有一个名为name
的字段。我希望这个字段包含在我的HomeLoanDistributionsDetails
模型中。因此,基本上,可以获得正确结果集的相应SQL查询如下:
SELECT D.name AS loan_group,
CONCAT(B.name,'/',B.fathers_or_husbands_name) AS customer_name_father_husband_Name ,
B.credit_card_no,B.membership_type AS Member_Class,
A.entry_date AS loan_date,
A.loan_amount,
A.service_charge,
A.security,
A.loan_taken_term,
E.name,
A.installment_amount,
A.installment_service_charge
FROM home_loan_distributions_details A
LEFT JOIN customers B ON A.customer_id = B.id
LEFT JOIN loan_groups_customers C ON B.id = C.customer_id
LEFT JOIN loan_groups D ON C.loan_group_id = D.id
LEFT JOIN home_loan_categories E ON A.category_id = E.id
WHERE A.customer_id = 18
GROUP BY A.id
我完全不知道如何使用模型类中现有的belongsTo
关联在我的模型类中执行以下操作:
LEFT JOIN loan_groups_customers C ON B.id = C.customer_id
LEFT JOIN loan_groups D ON C.loan_group_id = D.id
请注意,我的home_loan_distributions_details
表没有任何列,如loan_group_id
或loan_group
,这些列可以作为外键直接映射到loan_groups
表。这就是我问题背后的主要原因。
我在belongsTo
关联部分中尝试了这样的方法,但是得到了SQL (当然,正如预期的那样):
'LoanGroup' => array(
'className' => 'LoanGroup',
'foreignKey' => 'customer_id',
'fields' => 'id,name'
),
CakePHP版本- 1.2.5,5.2.11,MySQL版本- 5.1.36。
发布于 2014-11-30 13:51:05
您可以运行一个子查询,也可以使用ClassRegistry::init('region');
动态加载模型,并首先调用find,传入外键。不过,我推荐第一个,因为这样会更有效率。
https://stackoverflow.com/questions/27211927
复制相似问题