嘿,目前我们有一个从一个表(关系)中选择所有的数组,我们需要将 Accounts 表中的 account_name 放入该数组中。我们将如何做到这一点?
我们的关系表有(id、receiver_id、sender_id、active、expiry_date)。Receiver_id 和 sender_id 都是 account_id 的外键。
目前它工作正常,但打印了接收者和发送者的 ID,我们希望 Account 表中的 account_name 存在。
这是我们的函数、视图和模型:
功能:
//retrieve Account Id of current User
$accountid=$this->Auth->user('account_id');
//Conditions
$conditions=array("OR"=> array(
'Relationship.sender_id' => $accountid,
'Relationship.receiver_id' => $accountid));
//Find all Invoices where receiver_id = accountid
$relationships=$this->Relationship->find('all', array(
'conditions' => $conditions));
debug($relationships);
$this->set('accountid', $accountid);
$this->set('relationship', $relationships);
}
看法:
<table>
<tr>
<th>Relationship #</th>
<th>Sender</th>
<th>Receiver</th>
<th>Expiry Date</th>
<th>Status</th>
</tr>
<?php foreach($relationship as $relationships):?>
<?php
if($relationships['Relationship']['active']==1)
{
$status = 'Active';
}
else if($relationships['Relationship']['active']==0)
{
$status = 'Not Active';
}
?>
<tr>
<td align='center'><?php echo $relationships['Relationship']['id']; ?></td>
<td align='center'><?php echo $relationships['Relationship']['sender_id']; ?></td>
<td align='center'><?php echo $relationships['Relationship']['receiver_id']; ?></td>
<td align='center'><?php echo date('d.m.Y', strtotime($relationships['Relationship']['expiry_date'])); ?></td>
<td align='center'><?php echo $status ?></td>
</tr>
<?php endforeach; ?>
</table>
关系模型:
class Relationship extends AppModel
{
var $name = 'Relationship';
public $useTable = 'relationships';
public $primaryKey = 'id';
/*
public $hasMany = array(
'Invoice' =>
array(
'className' => 'Invoice',
'joinTable' => 'invoice',
'foreignKey' => 'invoice_id'));*/
//fix this code
public $belongsTo = array(
'User' =>array(
'className' => 'User',
'foreignKey' =>'receiver_id',
'associationForeignKey' => 'accounts_id',
));
var $validate = array(
'date' => array(
'rule' => array(
'datevalidation',
'systemDate'
),
'message' => 'Current Date and System Date is mismatched'
),
'receiver_id' => array(
'userExists' => array(
'rule' => array(
'userExists',
),
'message' => 'That username doesnt exist.'
),
),
);
function datevalidation($field = array(), $compare_field = null)
{
if ($field['date'] > $compare_field)
return TRUE;
else
return FALSE;
}
function accountExists($check)
{
$accountExists = $this->Account->find('count', array('conditions' => array('Account.id'=>$check)));
if ($accountExists == 1) {
return TRUE;
}
else
return FALSE;
}
}