如何根据find()调用更改包含的关联的连接类型?

时间:2016-04-02 14:10:34

标签: cakephp query-builder cakephp-3.2

如何重置不同位置的连接类型?

以下是我的表格:

租赁表

class TenancyTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('tenancy');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->belongsTo('Properties', [
            'foreignKey' => 'property_id',
            'className' => 'property',
            'joinType' => 'INNER'
        ]);

物业表

class PropertyTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('property');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Tenancies', [
            'foreignKey' => 'property_id',
            'className' => 'tenancy',
            'joinType' => 'LEFT'
        ]);

例如,将租期连接类型更改为右

 $setting = [
      'contain' => [
          'Tenancies' => [
              'joinType' => 'RIGHT'
          ]
      ]
 ];

$properties = $this->find('all', $setting)
       ->hydrate(false)
       ->select(['Property.id', 'Property.company_id', 'Property.address1', 'Property.postcode'])

1 个答案:

答案 0 :(得分:2)

您可以完全按照显示方式执行此操作,即在joinType设置中指定contain选项。

但是,由于您要从Property表进行查询,这将无效,因为在单独的查询中检索hasMany关联,因此不涉及任何联接。它适用于hasOnebelongsTo关联,这些关联在同一查询中被检索。