我想获取所有内容并将其显示在下表中的一个表中:
Petrolclaims表
$this->belongsTo('Workers', [
'foreignKey' => 'worker_id',
'joinType' => 'INNER'
//'through' => 'Selections'
]);
$this->belongsTo('Vehicles', [
'foreignKey' => 'vehicle_id',
'joinType' => 'INNER'
]);
Tollclaims表
$this->belongsTo('Workers', [
'foreignKey' => 'worker_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Vehicles', [
'foreignKey' => 'vehicle_id',
'joinType' => 'INNER'
]);
工人表
<?php
namespace App\Model\Table;
use App\Model\Entity\Worker;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* Workers Model
*
*/
class WorkersTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->hasMany('Petrolclaims', [
'className' => 'Petrolclaims'
]);
$this->hasMany('Tollclaims', [
'className' => 'Tollclaims'
]);
$this->table('workers');
$this->displayField('name');
$this->primaryKey('id');
}
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator)
{
$validator
->add('id', 'valid', ['rule' => 'numeric'])
->allowEmpty('id', 'create');
$validator
->requirePresence('name', 'create')
->notEmpty('name');
$validator
->add('createdDate', 'valid', ['rule' => 'datetime'])
->allowEmpty('createdDate', 'create');
return $validator;
}
}
车辆表
$this->hasMany('Petrolclaims', [
'className' => 'Petrolclaims'
]);
$this->hasMany('Tollclaims', [
'className' => 'Tollclaims'
]);
WorkersController
$results1 = $this->Workers->find('all')
->select([
'Petrolclaims.worker_id', 'Petrolclaims.vehicle_id'
'Tollclaims.worker_id', 'Tollclaims.vehicle_id',
'Workers.id',
'Vehicles.id'
])
->order(['Workers.name' => 'ASC'])
->contain([
'Tollclaims','Petrolclaims'
]);
我怎样才能做到这一点?
答案 0 :(得分:1)
看看是否有效:
$results1 = $this->Workers->find()
->select(['id','name'])
->contain([
'Petrolclaims'=>function ($q) {
return $q
->select(['id','worker_id','vehicle_id'])
->autoFields(false);
},
'Tollclaims'=>function ($q) {
return $q
->select(['id','worker_id','vehicle_id'])
->autoFields(false);
},
])
->order(['name' => 'ASC']);
// EDIT: hasMany data can be accesed by doing the following:
foreach ($results1 as $worker) {
echo $worker->petrolclaims[0]->vehicle_id;
}
注意:以上代码未经测试。
您无需从表Vehicles
获取数据,因为您只需要Vehicles.id
,它已包含在外键Petrolclaims.vehicle_id
和Tollclaims.vehicle_id
中。< / p>