CakePHP之前查找条件
我正在寻找非常直观的东西。
有多个带有数据的模型,每个记录都有一个 status
字段。因此,如果管理员我需要查看状态为“1”和“0”的所有记录,但对于前端,我需要设置一些全局 beforeFind
,它将仅查找状态为 status< 的数据/code>=1
还有一些模型 hasMany
和其他模型 belongsTo
,因此前端也应该过滤此数据,以仅显示具有 status
的数据代码>=1
I am looking for something very intuitive.
There are several models with data and each record has a status
field. So if admin I need to see all the records both with status '1' and '0' but for the frontend I need to set some global beforeFind
which will find only the data with status
=1
Also some of the models hasMany
and others belongsTo
so this data should also be filtered for the frontend to show only the data with status
=1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过在模型的
beforeFind
回调中添加一条规则来轻松完成此操作,该规则将添加'status' =>; 1
条件,除非已设置'status'
。因此您可以随时覆盖该条件,但它默认为1
。不过,您应该明确这些事情,而不是依赖神奇的回调行为。最好的方法是在模型中创建一个方法,例如
findPublicItems
,它将条件添加到条件数组中。在您只想显示status = 1
项的所有控制器方法中,显式调用此方法。在管理界面中,使用常规查找方法执行您想做的任何操作。You could do this easily by adding a rule in the model's
beforeFind
callback which adds'status' => 1
to the conditions, unless'status'
is already set. So you can override the condition at any time, but it'll default to1
.You should make such things explicit though, instead of relying on magic callback behavior. The best way would be to create a method in the model like
findPublicItems
, which adds the condition to the condition array. In all your controller methods where you only want to showstatus = 1
items, explicitly call this method. In the admin interface, do whatever you want using the regular find methods.