Cakephp:在表中显示包含其他表数据的数据

时间:2017-06-22 14:49:53

标签: cakephp orm associations cakephp-3.x

我在表格中显示我的用户,而我正在使用company_id检索公司名称和城市

用户:

id  lastname    firstname   company_id  role
1   doe         john        2           author
2   deo         jenne       2           admin
3   deus        Joe         1           admin
4   Stewart     Rob         1           author

公司:

id  name                city
1   New-York Company    New-York
2   Paris Company       Paris

用户显示:

            <?php 
                foreach($users as $user):?>
                <tr>
                    <td><?= $user->lastname?></td>
                    <td><?= $user->firstname?></td>
                    <td><?= $user->companies->name ?></td>
                    <td><?= $user->companies->city?></td>
                    <td><?= $user->role?></td>
                </tr>
                <?php endforeach;?>     

usersTable.php:

<?php
namespace App\Model\Table;

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

class UsersTable extends Table
{
    public function initialize(array $config){
        $this->belongsToMany('Companies');
        $this->belongsTo('Companies', [
        'foreignKey' => 'company_id',
    ]);
}

}       

?>

所以在我的公司展示中,我想检索管理员和作者姓名,如下所示:

                <?php 
                foreach($companies as $company):?>
                <tr>
                    <td><?= $company->name?></td>
                    <td><?= $company->city?></td>
                    <td><?= $company->users-> *adminlastname* ?></td>
                    <td><?= $company->users-> *adminfirstname* ?></td>
                    <td><?= $company->users-> *authorlastname* ?></td>
                    <td><?= $company->users-> *authorfirstname* ?></td>
                </tr>
                <?php endforeach;?>     

我已尝试获取公司ID以引用用户中的company_id,以便初学者走上正轨,但没有成功(尝试获取非对象的属性)

此外,如果我有几位作者和管理员,它会起作用吗?每个公司不太可能有几个管理员,但可能会发生,而且几个作者可能是可能的

公司表:

<?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;


}




 }

编辑:添加公司/ 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>

我收到了这些错误:

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):?> 

CompaniesController:

 <?php

namespace App\Controller;

use Cake\ORM\TableRegistry;


class CompaniesController extends AppController{

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

         $this->loadModel('Users');
        $users = $this->Users->find('all')
            ->contain(['companies']);
        $this->set(compact('users'));




    }

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

     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);
    }
 }

提前致谢

1 个答案:

答案 0 :(得分:2)

首先,您不能使用相同的名称定义多个关联。鉴于您有一个company_id字段,从用户的角度来看,这是一个belongsTo关联。

鉴于这些先决条件,从公司的角度来看,它自然是一个hasMany关联。我假设你已经在你的CompaniesTable课程中设置了它,如果没有,那么这就是你需要先做的事情。

users属性将是User条件对象的数组,因此您需要相应地访问它,即直接通过索引:

$company->users[0]->firstname

或迭代它:

foreach ($company->users as $user) {
    // $user->firstname
}

如果您需要处理由其角色分隔的用户,那么您可以相应地过滤它们:

$admins = collection($company->users)->filter(function ($user) {
    return $user->role === 'admin';
});

或者更好的是使用条件创建单独的关联:

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

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

通过这种方式,您可以单独包含和访问不同类型的用户:

$company->admins
$company->authors

另见