Welcome Guest, Not a member yet? Register   Sign In
array_column does not work with Entity
#1

(This post was last modified: 06-03-2024, 10:52 PM by warcooft.)

Hi everyone,
I have code like this:

PHP Code:
$notifications model(NotificationSettingModel::class)->withScheduleNotification()->find($userIds);

    if (empty($notifications)) {
         return false;
    }

$users model(UserModel::class)->find(array_column($notifications'user_id')); 


after running it, i got an error like this:
 
Code:
array_column(): Argument #1 ($array) must be of type array, App\Entities\NotificationSetting given


even though in version 4.4.8 the code above runs fine. but why doesn't it work on version 4.5.1?

i took an example from this repositori: 
https://github.com/lonnieezell/forum-exa...t.php#L121

Thanks All.
@xxxx[{::::::::::::::::::::::::::::::::>
Reply
#2

In top file strict_types=1 ?
Simple CI 4 project for beginners codeigniter-expenses ( topic )
Reply
#3

(06-04-2024, 07:22 AM)ozornick Wrote: In top file strict_types=1 ?

I didn't do that
@xxxx[{::::::::::::::::::::::::::::::::>
Reply
#4

(This post was last modified: 06-04-2024, 05:48 PM by kenjis.)

(06-03-2024, 10:36 PM)warcooft Wrote: after running it, i got an error like this:
 
Code:
array_column(): Argument #1 ($array) must be of type array, App\Entities\NotificationSetting given


even though in version 4.4.8 the code above runs fine. but why doesn't it work on version 4.5.1?

array_column() does not accept an object. So if it works in 4.4.8, there is something wrong with 4.4.8.
https://www.php.net/manual/en/function.array-column.php
You must pass an array to array_column().
Reply
#5

(This post was last modified: 06-04-2024, 07:37 PM by warcooft.)

(06-04-2024, 05:48 PM)kenjis Wrote:
(06-03-2024, 10:36 PM)warcooft Wrote: after running it, i got an error like this:
 
Code:
array_column(): Argument #1 ($array) must be of type array, App\Entities\NotificationSetting given


even though in version 4.4.8 the code above runs fine. but why doesn't it work on version 4.5.1?

array_column() does not accept an object. So if it works in 4.4.8, there is something wrong with 4.4.8.
https://www.php.net/manual/en/function.array-column.php
You must pass an array to array_column().

i dont know why this is not working. before upgrading to version 4.5.1 the code ran smoothly, in aboove repository it was also clear that the NotificationSettingModel model returned an Entity class then used with array_column() function.

This code also shows the entity as parameter in array_column function.
See https://github.com/lonnieezell/forum-exa...ry.php#L61
@xxxx[{::::::::::::::::::::::::::::::::>
Reply
#6

> in aboove repository it was also clear that the NotificationSettingModel model returned an Entity class then used with array_column() function.

No, no. It returns an array of Entities, not an Entity class instance.
Reply
#7

(This post was last modified: 06-04-2024, 08:31 PM by warcooft.)

(06-04-2024, 07:39 PM)kenjis Wrote: > in aboove repository it was also clear that the NotificationSettingModel model returned an Entity class then used with array_column() function.

No, no. It returns an array of Entities, not an Entity class instance.

Ok now I understand a bit, if I use the  $model->find([1,2,3]);  this method will return an entity object and if I use $model->whereIn('user_id', [1,2,3])->findAll( ); this will return an array of Entities. right?
Anyway, using the second method was solved my case.
@xxxx[{::::::::::::::::::::::::::::::::>
Reply
#8

(This post was last modified: 06-04-2024, 11:16 PM by warcooft.)

Looks like this is a bug:
Different behavior between models with primary key ID and not ID or something else when using find() method.

[Image: PvtOaA.jpg]


[Image: pPVEBu.jpg]
in NotificationSettingModel I use user_id as $primary_key

and UserModel uses id as $primary_key

it looks like the find() method uses id as the default reference.

why doesn't the find() method detect the primary key assigned to the model?

it would be more efficient than having to create chained methods like this model(NotificationSettingModel::class)->whereIn(user_id, [1,2,3])->findAll();

-------------------------------------------------------

PHP Code:
$notifications model(NotificationSettingModel::class)->find([46]);
$notifications model(NotificationSettingModel::class)->find(); 


The query above produces the same output as in the screenshot, is it because the method does not find the ID column in a table?
my expected output is It should returns an array of Entities.

[Image: lpxw0q.jpg]
after I debug again. the result query of this code model(NotificationSettingModel::class)->withScheduleNotification()->find([1, 2]);

meets my expectations, but why is the output object an entity, not an array of an entity?
@xxxx[{::::::::::::::::::::::::::::::::>
Reply
#9

> but why is the output object an entity, not an array of an entity?

I don't know, find([...]) should return an array.
I cannot reproduce the result.
Reply
#10

(This post was last modified: 06-05-2024, 01:02 AM by warcooft.)

Try with this migration, this only happens if the primary key is not an id as in general, then create 1 dummy data and run query builder method llike model(NotificationSettingModel::class)->find([1,2]);

PHP Code:
<?php

namespace App\Database\Migrations;

use 
CodeIgniter\Database\Migration;

class 
NotificationSettings extends Migration
{
    public function up()
    {
        $this->db->disableForeignKeyChecks();
        $this->forge->addField([
            'user_id' => [
                'type'      => 'INT',
                'constraint' => 12,
                'unsigned'  => true,
                'null'      => false,
            ],
            'email_schedule' => [
                'type'      => 'tinyint',
                'constraint' => 1,
                'unsigned'  => true,
                'null'      => false,
                'default'    => 1,
            ],
            'email_surat_tugas' => [
                'type'      => 'tinyint',
                'constraint' => 1,
                'unsigned'  => true,
                'null'      => false,
                'default'    => 1,
            ],
            'created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP',
            'updated_at' => ['type' => 'DATETIME''null' => true],
        ]);
        $attributes = ['ENGINE' => 'InnoDB'];
        $this->forge->addKey('user_id'truetrue);
        $this->forge->addForeignKey('user_id''users''id'false'CASCADE');
        $this->forge->createTable('notification_settings'true$attributes);
        $this->db->enableForeignKeyChecks();
    }

    public function down()
    {
        $this->forge->dropTable('notification_settings'falsetrue);
    }


here Entities:

PHP Code:
<?php

namespace App\Entities;

use 
CodeIgniter\Entity\Entity;

class 
NotificationSetting extends Entity
{
    protected $datamap = [];
    protected $dates  = ['created_at''updated_at'];


Models:

PHP Code:
<?php

namespace App\Models;

use 
App\Entities\NotificationSetting;
use 
CodeIgniter\Model;

class 
NotificationSettingModel extends Model
{
    protected $table            'notification_settings';
    protected $primaryKey      'user_id';
    protected $useAutoIncrement false;
    protected $returnType      NotificationSetting::class;
    protected $useSoftDeletes  false;
    protected $protectFields    true;
    protected $allowedFields    = [
        'user_id''email_schedule''email_surat_tugas',
    ];
    protected bool $allowEmptyInserts false;

    protected array $casts  = [
        'user_id'          => 'integer',
        'email_schedule'    => 'int-bool',
        'email_surat_tugas' => 'int-bool',
    ];

    // Dates
    protected $useTimestamps true;
    protected $dateFormat    'datetime';
    protected $createdField  'created_at';
    protected $updatedField  'updated_at';
    protected $deletedField  'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages  = [];
    protected $skipValidation      false;
    protected $cleanValidationRules true;

    // Callbacks
    protected $allowCallbacks true;
    protected $beforeInsert  = [];
    protected $afterInsert    = [];
    protected $beforeUpdate  = [];
    protected $afterUpdate    = [];
    protected $beforeFind    = [];
    protected $afterFind      = [];
    protected $beforeDelete  = [];
    protected $afterDelete    = [];

    /**
    * Get settings with active email thread notifications.
    */
    public function withScheduleNotification()
    {
        $this->groupStart()->where('email_schedule'1)->groupEnd();
        return $this;
    }

    /**
    * Get settings with active email thread notifications.
    */
    public function withSuratTugasNotification()
    {
        $this->where('email_surat_tugas'1);

        return $this;
    }

@xxxx[{::::::::::::::::::::::::::::::::>
Reply




Theme © iAndrew 2016 - Forum software by © MyBB