我正在使用 CakePHP 3 原生 ORM 来检索产品表的记录(按ID) 以及使用以下方法引用产品记录的记录:
public function view($id)
{
if($this->request->is('get'))
{
$product = $this->Products->get($id, [
'contain' => ['Stores', 'Bookings', 'ProductFeatures', 'ProductMedias']
]);
$this->set('product', $product);
$bannerType = 2;
$bannersQuantity = 1;
$fullBanners = $this->Search->listAllBanners($bannerType, $bannersQuantity);
$this->set('fullBanners', $fullBanners);
$logged = $this->Auth->user();
$this->set('logged', $logged);
$this->set('pageTitle', $product['product_name'].' - Stores');
}
}
这基本上返回了所有需要的记录,但是如何返回表功能中的每条记录 product_features 表中引用的内容?
表:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
store_id INT NOT NULL,
sub_category_id INT NOT NULL,
quantity INT NOT NULL,
sold INT NOT NULL,
description VARCHAR(1000),
price DECIMAL(7,2) NOT NULL,
old_price DECIMAL(7,2) NOT NULL,
visited INT NOT NULL,
thumbnail VARCHAR(255) NOT NULL,
status INT NOT NULL,
created DATETIME,
modified DATETIME,
FOREIGN KEY store_key (store_id) REFERENCES stores(id),
FOREIGN KEY sub_category_key (sub_category_id) REFERENCES sub_categories(id)
);
CREATE TABLE sub_categories (
id INT AUTO_INCREMENT PRIMARY KEY,
sub_category_name VARCHAR(255) NOT NULL,
category_id INT NOT NULL,
created DATETIME,
modified DATETIME,
FOREIGN KEY category_key (category_id) REFERENCES categories(id)
);
CREATE TABLE features (
id INT AUTO_INCREMENT PRIMARY KEY,
feature_name VARCHAR(255) NOT NULL,
created DATETIME,
modified DATETIME
);
CREATE TABLE product_features (
id INT AUTO_INCREMENT PRIMARY KEY,
feature_value VARCHAR(255) NOT NULL,
feature_id INT NOT NULL,
product_id INT NOT NULL,
created DATETIME,
modified DATETIME,
FOREIGN KEY feature_key (feature_id) REFERENCES features(id),
FOREIGN KEY product_key (product_id) REFERENCES products(id)
);
修改
public function initialize(array $config)
{
$this->table('products');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsTo('Stores', [
'foreignKey' => 'store_id',
'joinType' => 'INNER'
]);
$this->hasMany('Bookings', [
'foreignKey' => 'product_id'
]);
$this->hasMany('ProductFeatures', [
'foreignKey' => 'product_id'
]);
$this->hasMany('ProductMedias', [
'foreignKey' => 'product_id'
]);
}