I have a projects table and an images' table.
我有一个项目表和一个图像表。
A project has many images, so it's a one to many relationship between the two tables.
一个项目有很多图像,所以它是两个表之间的一对多关系。
In the images view I can retrieve the project name that is related to an image by using:
在图像视图中,我可以使用以下方法检索与图像相关的项目名称:
<?= $image->has('project') ? $this->Html->link($image->project->project_title, ['controller' => 'Projects', 'action' => 'view', $image->project->project_id]) : '' ?>
But now I want to do the same for the project view. I want to display all the images related to a specific project. But this doesn't work:
但现在我想为项目视图做同样的事情。我想显示与特定项目相关的所有图像。但这不起作用:
<?= $project->has('image') ? $this->Html->link($project->image->image_path, ['controller' => 'Images', 'action' => 'view', $project->image->image_path]) : '' ?>
Or do I need a many to many relation for this?
或者我需要多对多关系吗?
1 个解决方案
#1
Solution
In the ProjectsTable:
在ProjectsTable中:
$this->hasMany('Images', [
'foreignKey' => 'project_id',
'joinType' => 'INNER'
]);
In the ProjectsController:
在ProjectsController中:
$project = $this->Projects->get($id, [
'contain' => ['Categories', 'Users', 'Tags', 'Images']
]);
In the Projects > view.ctp
在Projects> view.ctp中
<?php foreach ($project->images as $images): ?>
<p><?= h($images->image_path) ?></p>
<?php endforeach; ?>
#1
Solution
In the ProjectsTable:
在ProjectsTable中:
$this->hasMany('Images', [
'foreignKey' => 'project_id',
'joinType' => 'INNER'
]);
In the ProjectsController:
在ProjectsController中:
$project = $this->Projects->get($id, [
'contain' => ['Categories', 'Users', 'Tags', 'Images']
]);
In the Projects > view.ctp
在Projects> view.ctp中
<?php foreach ($project->images as $images): ?>
<p><?= h($images->image_path) ?></p>
<?php endforeach; ?>