如何从 Joomla 组件的布局内部运行 SQL 查询
我仍在学习制作 Joomla 组件,但我遇到了一种情况,在我迄今为止读过的任何教程或书籍中都找不到答案。 我有一个模型(在 models/weather.php 中),它有一个方法 getData()。这个方法是从视图(在views/view.html.php中)调用的,它从我的数据库中获取一系列记录。 然后使用 foreach 循环在我的布局 (views/tmpl/default.php) 中迭代此范围的记录,如下所示:
if ($this->item) {
foreach ($this->item as $item) {
//...
}
}
我需要做的是在我想要的注释点 (//...)根据 $item->id 的值从另一个表中检索其他记录。我的问题是如何根据最佳实践来做到这一点?我想我可以直接打开数据库并获取我需要的数据,但我怀疑在基于 MVC 的程序中我需要将此查询放入函数或方法中?我应该把它放在哪里以及如何访问它?一个例子的链接将不胜感激。
答案: 我真是个白痴。显然,我可以从布局中的视图调用任何方法,并且在该方法中我可以访问我的模型(我可以在其中创建查找函数)。有时我的思维(仍然)过于程序化,无法简单地“看到”OOP。
I am still learning to make a Joomla component, but I have run into a situation which I cannot find the answer to in any tutorial or book I have read so far.
I have a Model (in models/weather.php) which has a method getData(). This method is called from View (in views/view.html.php) and this gets a range of records from my database.
This range of records is then iterated through in my layout (views/tmpl/default.php) using a foreach loop, something like this:
if ($this->item) {
foreach ($this->item as $item) {
//...
}
}
What I need to do is at the point of the comment (//...) I want to retrieve some other record from another table based on the value of $item->id. My question is how do I do this according to best practice? I suppose I could just open up the database right there and get the data I need, but I am suspecting that in a MVC based program I need to put this query in a function or method? Where do I put this and how do I access it? A link to an example would be much appreciated.
ANSWER:
I am such an idiot. Obviously I can just call any method from the view in my layout and in that method I can access my Model (where I can create the lookup function). Sometimes my mind is (still) too procedural to simply 'see' OOP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在布局(default.php)中处理数据是不好的做法。布局应仅通过视图(view.html.php)显示已从模型检索和处理的数据。为什么不向模型添加另一个方法并从
getData
调用该方法?那就好多了。It is bad practice to process data in the layout(default.php). Layout should only display already retrieved and processed data from model via view(view.html.php). Why don't you add another method to your model and call that method from
getData
? It would be much better.您可以在其他模型中编写一个方法,从其中提取数据,例如 getMyItem()。然后在您看来,您需要像
编写逻辑一样获取模型以在模型的方法中获取 Myitem
you can write a method in your other model from where you want to pull data like getMyItem(). Then in your view you would need to get the model like
Write logic to get Myitem in model's method