Cakephp 3 ORM:错误的关联?

Cakephp 3 ORM : wrong associations?

所以我问了一个关于如何显示2个表的数据的问题 here。 帮助我的人似乎在指出,如果我的协会完成了,它应该会起作用。 但作为新手,我不明白为什么它不起作用。

我收到以下错误:

Notice (8): Undefined variable: company [APP/Template/Companies/index.ctp, line 36]
Notice (8): Trying to get property of non-object [APP/Template/Companies/index.ctp, line 36]
Warning (2): Invalid argument supplied for foreach() [APP/Template/Companies/index.ctp, line 36]

对应于此:

 <?php foreach ($company->users as $user):?> 

在我的 Companies/index.ctp 中:

 <div class="row">
        <div class="medium-4 small-12 columns">
        <div style="padding: 22px;">
            <h2>companies</h2>

        </div>

    <div id="customAdd" style="clear:both;padding: 22px;">
            <a href="/companies/add" class="button secondary right" data-reveal-id="Modal" data-reveal-ajax="true">add</a>          
 <div style="clear:both;height:0px;"></div>
    </div>



         <div id="customSearch" style="clear: both;padding: 22px">
            <p style="font-size:36px;    display: inline-block;">search for a company</p><input type="text" id="searchBox">
        </div>


    </div>
     <div class="medium-8 small-12 columns">
        <div>

             <table id="companies" class="cell-border dataTable no-footer">
                <thead>
                    <tr>
                        <th>name</th>
                        <th>city</th>
                        <th>last name</th>
                        <th>first name</th>

                    </tr>
                </thead>
                <tbody>
                  <?php foreach ($company->users as $user):?> 

                    <tr class='clickable-row' data-href="/companies/edit/<?= $company->id?>">

                  <td><?= $company->name?></td>
                  <td><?= $company->city?></td>
                  <td><?= $company->users[0]->lastname?></td>
                  <td><?= $company->users[0]->firstname?></td>

                  </tr>
                  <?php endforeach;?>
                </tbody>
            </table>

        </div>
    </div>
</div>

公司控制器:

 <?php

 namespace App\Controller;

 use Cake\ORM\TableRegistry;


 class CompaniesController extends AppController{

public function index(){
    $companies = $this->Companies
    ->find('all', [
        'order' => ['Companies.name' => 'ASC'],
        'contain' => ['Users'],
    ]
  );

    $this->set(compact('companies'));


}

public function view($id = null){
    $companies = $this->Companies->get($id);
    $this->set(compact('companies'));
}

     public function add(){
        $company = $this->Companies->newEntity();
         if ($this->request->is('post')) {

             if ($this->Companies->save($company)) {

                 $this->Flash->success(__('Your company has been saved.'));

                return $this->redirect(['action' => 'index']);
             }
            $this->Flash->error(__('Unable to add your company.'));
        }
        $this->set('company', $company);

         $this->set(compact('companies'));
    }

     public function edit($id = null){
        $company = $this->Companies->get($id);
        if ($this->request->is(['post', 'put'])) {
            $company = $this->Companies->patchEntity($company, $this->request->data,['associated' => ['Users']]);


            if ($this->Companies->save($company)) {



                $this->Flash->success(__('Your company has been updated.'));
                return $this->redirect(['action' => 'index']);
            }

             $this->Flash->error(__('Unable to update your company.'));
        }


        $this->set('company', $company);

        $this->set(compact('companies'));

    }

    public function delete($id){
        $this->request->allowMethod(['post', 'delete']);
         $company = $this->Companies->get($id);
         if ($this->Companies->delete($company)) {
            $this->Flash->success(__('The company with id: {0} has been deleted.', h($id)));
            return $this->redirect(['action' => 'index']);
        }
     }

     public function isAuthorized($user){
         if ($this->request->action === 'logout') {
            return true;
        }
         if ($this->request->action === 'settings') {
            return true;
         }
          return parent::isAuthorized($user);
    }
 }

公司表:

<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class companiesTable extends Table
{

public function initialize(array $config){
    //$this->addBehavior('Timestamp');
    $this->hasMany('Users');
    $this->hasMany('companies', [
        'foreignKey' => 'identite',
    ]);
    $this->hasMany('Admins', [
'className' => 'Users',
'conditions' => [
    'Admins.role' => 'admin'
    ]
]);

$this->hasMany('Authors', [
     'className' => 'Users',
    'conditions' => [
        'Admins.role' => 'author'
    ]
]);


}

public function isOwnedBy($companyId, $userId){
    $company = $this
        ->find('all',['conditions' => ['companies.id'=>$companyId]])
        ->matching('Users', function ($q) use ($userId) {
            return $q->where(['Users.id' => $userId]);
        })
        ->first();
    if ($company) return true;
    return false;


}




 }

欢迎提问

编辑 2:

很迷茫...我在 index.ctp 中这样做:

 <?php $x =0; 
                foreach ($companies->users as $user):?>
                <tr class='clickable-row' data-href="companies/edit/<?= $companies->id?>">

              <td><?= $companies->users[$x]->name?></td>
              <td><?= $companies->users[$x]->city?></td>
              <td><?= $companies->users[$x]->admins?></td>
              <td><?= $companies->users[$x]->authors?></td>
              </tr>
              <?php $x++;
             endforeach;?>

我得到了这些错误:

 Notice (8): Undefined property: Cake\ORM\Query::$users 
 Warning (2): Invalid argument supplied for foreach()

这仍然对应于我的 foreach()

我的 CompaniesController 索引和视图函数:

public function index(){
    $companies = $this->Companies 
    ->find('all', [
        'order' => ['Companies.name' => 'ASC'],
        'contain' => ['Users'],
    ]
);

    $this->set(compact('companies'));


}

public function view($id = null){
    $company = $this->Companies->get($id);
    $this->set(compact('company'));
}

我的公司表:

<?php
namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class CompaniesTable extends Table
{

public function initialize(array $config){
$this->hasMany('Users');


$this->hasMany('Admins', [
'className' => 'Users',
'conditions' => [
    'Admins.role' => 'admin'
]
]);

$this->hasMany('Authors', [
'className' => 'Users',
'conditions' => [
    'Admins.role' => 'author'
]
]);


}

public function isOwnedBy($companyId, $userId){
    $company= $this
        ->find('all',['conditions' => ['companies.id'=>$companyId]])
        ->matching('Users', function ($q) use ($userId) {
        return $q->where(['Users.id' => $userId]);
        })
    ->first();
if ($company) return true;
return false;


 }




 }

您正在用户控制器的索引方法中设置变量 $companies,但在视图中引用 $company

如果您在视图中引用 $companies,它应该可以工作。

您可以使用contain 指定加载哪些关联数据。

$companies = $this->Companies
        ->find('all', [
            'order' => ['Companies.name' => 'ASC'],
            'contain' => ['Users'],
        ]
);

您可以阅读有关检索数据的更多信息in the docs

我认为问题在于您尝试访问对象属性的方式。尝试这样的事情:

foreach ($companies as $company) {
    $company->users; // each company has many users

    // if you want to loop over each company's users
    foreach ($company->users as $user) {
        //etc
    }
}