从Cake php 3中的表链接和显示数据

我正在尝试在我的jobs / index.ctp中显示类型表中的名称


不确定如何回声,到目前为止,我已经写了这个


但它不起作用,但也没有给出任何错误信息


class Jobs extends Table

{


    public function initialize(array $config)

    {

        parent::initialize($config);


        $this->setTable('jobs');

        $this->setDisplayField('title');

        $this->setPrimaryKey('id');


        $this->addBehavior('Timestamp');


        $this->belongsTo('Categories', [

            'foreignKey' => 'category_id',

            'joinType' => 'INNER'

        ]);

        $this->belongsTo('Users', [

            'foreignKey' => 'user_id',

            'joinType' => 'INNER'

        ]);

        $this->belongsTo('Types', [

            'foreignKey' => 'type_id',

            'joinType' => 'INNER'

        ]);

    }

class Types extends Table

{

    /**

     * Initialize method

     *

     * @param array $config The configuration for the Table.

     * @return void

     */

    public function initialize(array $config)

    {

        parent::initialize($config);


        $this->setTable('types');

        $this->setDisplayField('name');

        $this->setPrimaryKey('id');


        $this->hasMany('Jobs', [

            'foreignKey' => 'type_id'

        ]);

    }

<?php

foreach ($jobs as $jobs):

?>

<li>

    <div class="type"><span style="background:"> <?php echo $jobs['types']['name']; ?> </span></div>

    <div class="description">

        <h5><?php echo $jobs['title']; ?> (<?php echo $jobs['city']; ?> , <?php echo $jobs['postcode']; ?>)</h5>

        <h6><strong>company Name: <?php echo $jobs['company_name']; ?></strong></h6>

        <h6>Date Posted:<span id="list_date"> <?php echo $this->Time->Format($jobs['created'], "d MMMM y") ?> </span></h6>

一切都在这行之外 <?php echo $jobs['types']['name'] ;?>


慕村225694
浏览 141回答 2
2回答

素胚勾勒不出你

要显示关联的表数据,您需要做三件事:表中的关联$this->belongsTo('Types', [&nbsp; &nbsp; 'foreignKey' => 'type_id',&nbsp; &nbsp; 'joinType' => 'INNER']);在控制器(JobsController)中,使用“ contain”指定关联表,public function index() {&nbsp; &nbsp; $jobs = $this->Jobs->find('all')->contain(['Types']);&nbsp; &nbsp; //set jobs variable to make it available in .ctp file&nbsp;}在Jobs / index.ctp文件中<?php echo $job['types']['name'] ;?>

万千封印

首先,您的foreach循环应为foreach ($jobs as $job)。请注意$job跟踪每个特定作业的变量的单数形式。紧接着,由于“作业belongTo类型”,每个作业只有一个类型,而不是多个。结果,您正在寻找的值是&nbsp;$job['type']['name']($job->type->name可能也可以使用)。所有这些都假定您在加载记录时已正确使用了遏制;因此,为什么我也要求显示该代码。如果乔布斯有许多类型,那么您将拥有$job['types'](或$job->types),它是可以迭代的Type实体的数组。
打开App,查看更多内容
随时随地看视频慕课网APP