【问题标题】:Find records from database based on second table using cakephp 3 [duplicate]使用cakephp 3根据第二个表从数据库中查找记录[重复]
【发布时间】:2017-04-06 12:14:14
【问题描述】:

我有两个表“类别”和“项目”

categories -> 
id  |   title
1   |   cat-1
2   |   cat-2 

items ->
id  |   title   |   category_id |   score
1   |   item-1  |   1           |   4
2   |   item-2  |   1           |   5
3   |   item-3  |   1           |   3
4   |   item-4  |   2           |   4
5   |   item-5  |   2           |   5
6   |   item-6  |   2           |   6

我想通过 apply limit(2) 获得结果,并使用 cakephp 3 在“items”表上按分数排序 输出喜欢 -

{
    "cat-1": {
        "0": {
            "id": 2,
            "title": "item-2",
            "score": "5"
        },
        "1": {
            "id": 1,
            "title": "item-1",
            "score": "4"
        },
    "cat-2": {
        "2": {
            "id": 6,
            "title": "item-6",
            "score": "6"
        },
        "3": {
            "id": 5,
            "title": "item-5",
            "score": "5"
        }
    }

【问题讨论】:

  • 你想要一个查询Mysql以这种方式提取数据吗?

标签: php mysql cakephp cakephp-3.0 cakephp-2.3


【解决方案1】:

使用contain

$this->Categories->find()
    ->contain([
        'Item' => function($q) {
            return $q->find()
                ->order(['score' => 'asc'])
                ->limit(2);
        }
    ]);

未经测试 - 对 iPhone 发表评论。 ;)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多