duanbiaoshu2021 2017-02-14 09:21
浏览 46
已采纳

Cakephp 3:contains()函数结果嵌套数据

Problem:

I want to run this query in cakephp 3

SELECT 
    medicine_records.*, 
    medicines.name AS medicine_name, 
    medicines.subname AS `medicine_subname` 
FROM medicine_records 
INNER JOIN medicines ON medicines.id = medicine_records.medicine_id

Controller:

$medicines = $this->MedicineRecords->find()->contain(['Medicines'])->all();

Cakephp Queries log:

2017-02-14 09:58:47 Debug: duration=1 rows=1 SELECT MedicineRecords.id AS `MedicineRecords__id`, MedicineRecords.user_id AS `MedicineRecords__user_id`, MedicineRecords.medicine_id AS `MedicineRecords__medicine_id`, MedicineRecords.times_pre_day AS `MedicineRecords__times_pre_day`, MedicineRecords.created AS `MedicineRecords__created`, MedicineRecords.modified AS `MedicineRecords__modified`, Medicines.id AS `Medicines__id`, Medicines.name AS `Medicines__name`, Medicines.subname AS `Medicines__subname`, Medicines.type AS `Medicines__type`, Medicines.created AS `Medicines__created`, Medicines.modified AS `Medicines__modified` FROM medicine_records MedicineRecords INNER JOIN medicines Medicines ON Medicines.id = (MedicineRecords.medicine_id)

Result data:

"data": [
    {
        "id": 1,
        "user_id": 1,
        "medicine_id": 3,
        "times_pre_day": 2,
        "created": "2017-02-14T04:55:48+00:00",
        "modified": "2017-02-14T04:55:48+00:00",
        "medicine": {
            "id": 3,
            "name": "Name",
            "subname": "Subname",
            "type": 1,
            "created": "2017-02-13T09:38:48+00:00",
            "modified": "2017-02-13T09:38:48+00:00"
        }
    }
]

This result has medicine in child level. I want all data in top level like this:

"data": [
  {
    "id": 1,
    "user_id": 1,
    "medicine_id": 3,
    "times_pre_day": 2,

    "medicine_name": "Name",
    "medicine_subname": "Subname",

    "created": "2017-02-14T04:55:48+00:00",
    "modified": "2017-02-14T04:55:48+00:00",
  }
]

I already try to use public $recursive = -1; but I think it not working on Cakephp 3.

Update

Remove WHERE medicine_records.id = 1

  • 写回答

1条回答 默认 最新

  • douzhan2027 2017-02-14 09:48
    关注

    Obviously that is the expected result,contain come in nested form and it should come this way.

    No worries you can select fields within contain as you need:

    $medicines = $this->MedicineRecords->find()
            ->contain(['Medicines' => function ($q) {
               return $q
                    ->select(['medicine_name'=>'name','medicine_subname'=>'subname']);
            }])->all();
    

    See Here (select within contain CakePHP 3).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题