我正在阅读CakePHP文档,但不确定是否需要使用find
以外的其他方法。示例:
在我的控制器中,我想提供Orders
的过滤列表,其中相关表state
的{{1}}字段为“ Open”:
OrderStates
但它表示找不到列$orders = $this->ItemsDeliveryNotes->Orders->find('list', [
'limit' => 200,
'conditions' => ['Orders.order_state.state' => 'Open'],
'contain' => ['OrderStates']
]);
。
这里的表order_state
的定义:
创造
Orders
实体
CREATE TABLE orders (
id int(11) NOT NULL AUTO_INCREMENT,
customer_id int(11),
orderNumber varchar(255) NOT NULL,
orderDate date,
order_state_id int(11),
PRIMARY KEY (id),
KEY order_state_id (order_state_id),
CONSTRAINT orders_ibfk_1 FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT orders_ibfk_2 FOREIGN KEY (order_state_id) REFERENCES order_states (id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
表
class Order extends Entity
{
protected $_accessible = [
'orderNumber' => true,
'orderDate' => true,
'customer_id' => true,
'order_state_id' => true,
'customer' => true,
'order_state' => true,
'items' => true
];
}
和public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('orders');
$this->setDisplayField('orderNumber');
$this->setPrimaryKey('id');
$this->belongsTo('Customers', [
'foreignKey' => 'customer_id'
]);
$this->belongsTo('OrderStates', [
'foreignKey' => 'order_state_id'
]);
$this->hasMany('Items', [
'foreignKey' => 'order_id'
]);
}
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['order_state_id'], 'OrderStates'));
$rules->add($rules->existsIn(['customer_id'], 'Customers'));
return $rules;
}
:
创造
OrderStates
实体
CREATE TABLE order_states (
id int(11) NOT NULL AUTO_INCREMENT,
state varchar(255) NOT NULL,
badge varchar(255) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
表
class OrderState extends Entity
{
protected $_accessible = [
'state' => true,
'badge' => true
];
}
在public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('order_states');
$this->setDisplayField('state');
$this->setPrimaryKey('id');
}
中可以访问列order_state
,并且我还将相关表(Orders
)添加到了OrderStates
选项中。我还想念什么?
答案 0 :(得分:-1)
@在您所包含实体的条件中标记问题。请确定您使用的是哪个Cakephp版本。
下面是使用contained table
条件的示例
传递要包含的条件
// Prior to 3.5.0 you would use contain(['Comments' => function () { ... }])
$query = $articles->find()->contain('Comments', function (Query $q) {
return $q
->select(['body', 'author_id'])
->where(['Comments.approved' => true]);
});
注意:确保已将use Cake\ORM\Query;
包括在“名称空间”部分。
有关更多详细信息,请参阅此处的文档。 https://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#passing-conditions-to-contain
对于您的情况,可能是这样的。
$orders = $this->ItemsDeliveryNotes->Orders->find('list', [ 'limit' => 200 ])->contain('OrderStates', function (Query $q) { return $q->where(['state' => 'Open']); });
答案 1 :(得分:-1)
以下是可使用的语法:
$orders = $this->ItemsDeliveryNotes->Orders->find('list', [ 'limit' => 200 ])
->contain('OrderStates')->where(['state' => 'Open']);