Reputation: 159
I have got two tables in my database. The Jobs are meant to be used as a list of available jobs, which should be categorized in different business genres.
jobs
id(int) PRIMARY
title(varchar)
business_id(int)
start(datetime)
description(text)
business
id(int) PRIMARY
name(varchar)
In jobs index I would like to show a list of all Jobs and their categories. But I am getting stuck on receiving the business name from the jobs controller.
JobsTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class JobsTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$this->HasOne('Business', ['foreignKey' => 'business_id']);
}
}
BusinessTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
class BusinessTable extends Table
{
public function initialize(array $config)
{
$this->hasMany('Jobs', ['foreignKey' => 'id']);
}
}
JobsController.php
public function index()
{
$jobs = $this->Jobs->find('all');
$this->set(compact('jobs'));
}
What do I have to do to use the business name from the business table inside my JobsController and its views?
Upvotes: 0
Views: 511
Reputation: 159
Thanks to prats1411 for his fast anwser.
I recently found a way to get it working for me. If somebody is able to provide a better solution, I would really recommend that.
in src/Model/Table/JobsTable.php:
$this->belongsTo('Business', ['foreignKey' => 'business_id']);
in src/Controller/JobsController.php:
$jobs = $this->Jobs->find('all')->contain('Business');
So i could finally show the Business name with $job->busines->name
inside my view.
Upvotes: 1
Reputation: 162
In your view of Jobs, you can try something like this
foreach($jobs as $job) :
echo $job->has('business') ? $this->Html->link($job->business->name, ['controller' => 'Businesses', 'action' => 'view', $job->business->id]) : ''
endforeach;
Upvotes: 1