PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 9, 2022

[FIXED] Get one column in CakePHP 3.x controller

 January 09, 2022     arrays, cakephp, cakephp-3.0     No comments   

Issue

How to get one colum with sql and convert it in array and use in controller?

$allid = $this ->TabelName
            ->find('list',array(
                'fields' => array('id'),
                'conditions' => array(
                    'User_id' => '1'
                )
            ));
        $this->set(compact('allid'));



        $data = $allid->toArray();
        echo $data;

What i need is to have in controller this $data=array("1","2","3"); and this are all ids from TableName. Can someone tell me how can i do this?


Solution

In cake 3 you can use Collections

$allid = $this ->TableName->find()
    ->select(['id'])
    ->where(['User_id' => '1']);

$allid = $allid
    ->extract('id')
    ->toArray();

see the manual here

instead of extract - if you need to obtain a string representing the array - you can use map and reduce()

$allid = $allid
   ->map(function ($value, $key) {
        return '"'.$value->id.'"';
    })
    ->reduce(function ($accumulated, $value) {
        return $accumulated.", " .$value;
    });


Answered By - arilia
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing