如何避免控制器cakephp中的自连接条件3

时间:2016-07-20 07:41:37

标签: cakephp-3.0

如果您不想在每个控制器的任何位置使用条件来选择模型,那么请使用以下代码

1 个答案:

答案 0 :(得分:0)

使用以下过程在模型中设置自联接。

使用控制器分配条件值如下...     

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Routing\Router;
use Cake\I18n\Time;
/**
 * Applications Controller
 *
 * @property \App\Model\Table\ApplicationsTable $Applications
*/
class ApplicationsController extends AppController
{
  public function initialize()
  {     
    parent::initialize();       
    $Applications = TableRegistry::get('Applications');
    $Applications->session = $this->Auth->user();       
  }
}

?>

表格中的使用条件如下...

<?php
 namespace App\Model\Table;

 use App\Model\Entity\Application;
 use Cake\ORM\Query;
 use Cake\ORM\RulesChecker;
 use Cake\ORM\Table;
 use Cake\Validation\Validator;
 use Cake\Event\Event;

/**
* Applications Model
*
* @property \Cake\ORM\Association\BelongsTo $Masterschools
*/
class ApplicationsTable extends Table
{

 public $session = null;
    /**
 * Initialize method
 *
 * @param array $config The configuration for the Table.
 * @return void
 */
public function initialize(array $config)
{
    $this->table('applications');
    $this->displayField('name');
    $this->primaryKey('id');

    $this->belongsTo('Masterschools', [
        'foreignKey' => 'masterschools_id',
        'joinType' => 'INNER'
    ]);        
}


function beforeFind(Event $event, Query $query, $options, $primary) {
    if($this->session['role'] != 'SuperAdministrator'){
        $query->where(['Applications.masterschools_id' => $this->session['masterschools_id']]);
    }       
    return $query;
}

}
?>