avenirer / CodeIgniter-MY_Model

Base model (MY_Model) for the Codeigniter framework.
324 stars 203 forks source link

has_many relationship record not found #289

Closed Hothi-Jimit closed 5 years ago

Hothi-Jimit commented 5 years ago

Hello,

its great work many many thank you all,

But i have one question

i run query

$data['users_with_count_many'] = $this->user_model->with_posts('fields:title')->with_details('fields:last_name,address,first_name')->as_array()->get_all();

output is

Array
        (
                [0] => Array
                (
                        [id] => 1
                        [username] => user1
                        [email] => user1@user.com
                        [password] => mypass
                        [created_at] =>
                        [created_by] =>
                        [updated_at] =>
                        [updated_by] =>
                        [deleted_at] =>
                        [deleted_by] =>
                        [posts] => Array
                        (
                                [0] => stdClass Object
                                (
                                        [user_id] => 1
                                        [title] => First title
                                        )

                                )

                        [details] => stdClass Object
                        (
                                [user_id] => 1
                                [last_name] => Doe
                                [address] => no stable address
                                [first_name] => John
                                )

                        )

                [1] => Array
                (
                        [id] => 2
                        [username] => user2
                        [email] => user2@user.com
                        [password] => nopass
                        [created_at] =>
                        [created_by] =>
                        [updated_at] =>
                        [updated_by] =>
                        [deleted_at] =>
                        [deleted_by] =>
                        [details] => stdClass Object
                        (
                                [user_id] => 2
                                [last_name] => Doe
                                [address] => same as John Doe's
                    [first_name] => Jane
                )

        )

    [2] => Array
        (
            [id] => 3
            [username] => avenirer
            [email] => user3@user.com
            [password] => nopass
            [created_at] =>
            [created_by] =>
            [updated_at] =>
            [updated_by] =>
            [deleted_at] =>
            [deleted_by] =>
            [posts] => Array
                (
                    [0] => stdClass Object
                        (
                            [user_id] => 3
                            [title] => Another title
                        )

                    [1] => stdClass Object
                        (
                            [user_id] => 3
                            [title] => One more title
                        )

                )

            [details] => stdClass Object
                (
                    [user_id] => 3
                    [last_name] => Voicu
                    [address] => Bucharest, Romania
                    [first_name] => Adrian
                )

        )

    [3] => Array
        (
            [id] => 4
            [username] => administrator
            [email] => user4@user.com
            [password] => mypass
            [created_at] =>
            [created_by] =>
            [updated_at] =>
            [updated_by] =>
            [deleted_at] =>
            [deleted_by] =>
            [details] => stdClass Object
                (
                    [user_id] => 4
                    [last_name] => Istrator
                    [address] => over us
                    [first_name] => Admin
                )

        )

    [4] => Array
        (
            [id] => 5
            [username] => user5
            [email] => user5@user.com
            [password] => nopass
            [created_at] =>
            [created_by] =>
            [updated_at] =>
            [updated_by] =>
            [deleted_at] =>
            [deleted_by] =>
            [posts] => Array
                (
                    [0] => stdClass Object
                        (
                            [user_id] => 5
                            [title] => This one has a title too
                        )

                    [1] => stdClass Object
                        (
                            [user_id] => 5
                            [title] => How about this title
                        )

                )

            [details] => stdClass Object
                (
                    [user_id] => 5
                    [last_name] => You want
                    [address] => Wherever
                    [first_name] => Whoever
                )

        )

)

my question is

if no record found in has many relationship so i want to return blank array or object

so how i can do it that ?

Thank you

salain commented 5 years ago

Hi, Adding a where clause to with_* should do it: $this->user_model->with_posts('fields:title','where:title IS NOT NULL')->with_details('fields:last_name,address,first_name','where:last_name IS NOT NULL')->as_array()->get_all();

Hothi-Jimit commented 5 years ago

i need all user data but when that user post not available then post return blank array or object.

in your solutions not provide all user data.

salain commented 5 years ago

Sorry I misunderstood. You will have to check if the post array/objet exist or not before working with it.

Hothi-Jimit commented 5 years ago

i want this type output

 Array
(
    [0] => Array
        (
            [id] => 1
            [username] => user1
            [email] => user1@user.com
            [password] => mypass
            [created_at] => 
            [created_by] => 
            [updated_at] => 
            [updated_by] => 
            [deleted_at] => 
            [deleted_by] => 
            [posts] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 1
                            [user_id] => 1
                            [title] => First title
                            [content] => This is content for first title
                        )

                )

            [details] => stdClass Object
                (
                    [user_id] => 1
                    [first_name] => John
                    [last_name] => Doe
                    [address] => no stable address
                    [created_at] => 
                    [created_by] => 
                    [updated_at] => 
                    [updated_by] => 
                    [deleted_at] => 
                    [deleted_by] => 
                )

        )

    [1] => Array
        (
            [id] => 2
            [username] => user2
            [email] => user2@user.com
            [password] => nopass
            [created_at] => 
            [created_by] => 
            [updated_at] => 
            [updated_by] => 
            [deleted_at] => 
            [deleted_by] => 
            [posts] => Array()
            [details] => stdClass Object
                (
                    [user_id] => 2
                    [first_name] => Jane
                    [last_name] => Doe
                    [address] => same as John Doe's
                    [created_at] => 
                    [created_by] => 
                    [updated_at] => 
                    [updated_by] => 
                    [deleted_at] => 
                    [deleted_by] => 
                )

        )

    [2] => Array
        (
            [id] => 3
            [username] => avenirer
            [email] => user3@user.com
            [password] => nopass
            [created_at] => 
            [created_by] => 
            [updated_at] => 
            [updated_by] => 
            [deleted_at] => 
            [deleted_by] => 
            [posts] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 2
                            [user_id] => 3
                            [title] => Another title
                            [content] => This is content for another title
                        )

                    [1] => stdClass Object
                        (
                            [id] => 3
                            [user_id] => 3
                            [title] => One more title
                            [content] => This is content for one more title
                        )

                )

            [details] => stdClass Object
                (
                    [user_id] => 3
                    [first_name] => Adrian
                    [last_name] => Voicu
                    [address] => Bucharest, Romania
                    [created_at] => 
                    [created_by] => 
                    [updated_at] => 
                    [updated_by] => 
                    [deleted_at] => 
                    [deleted_by] => 
                )

        )

    [3] => Array
        (
            [id] => 4
            [username] => administrator
            [email] => user4@user.com
            [password] => mypass
            [created_at] => 
            [created_by] => 
            [updated_at] => 
            [updated_by] => 
            [deleted_at] => 
            [deleted_by] => 
            [posts] => Array()
            [details] => stdClass Object
                (
                    [user_id] => 4
                    [first_name] => Admin
                    [last_name] => Istrator
                    [address] => over us
                    [created_at] => 
                    [created_by] => 
                    [updated_at] => 
                    [updated_by] => 
                    [deleted_at] => 
                    [deleted_by] => 
                )

        )

    [4] => Array
        (
            [id] => 5
            [username] => user5
            [email] => user5@user.com
            [password] => nopass
            [created_at] => 
            [created_by] => 
            [updated_at] => 
            [updated_by] => 
            [deleted_at] => 
            [deleted_by] => 
            [posts] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 4
                            [user_id] => 5
                            [title] => This one has a title too
                            [content] => This is content for this title too
                        )

                    [1] => stdClass Object
                        (
                            [id] => 5
                            [user_id] => 5
                            [title] => How about this title
                            [content] => This is content for how about this title
                        )

                )

            [details] => stdClass Object
                (
                    [user_id] => 5
                    [first_name] => Whoever
                    [last_name] => You want
                    [address] => Wherever
                    [created_at] => 
                    [created_by] => 
                    [updated_at] => 
                    [updated_by] => 
                    [deleted_at] => 
                    [deleted_by] => 
                )

        )

)

like index 2 post Array blank.

salain commented 5 years ago

Yes, I got it. The only way is to loop on the result and check if post exist if not add it. Or as I suggested before before using it check if it exists.

Hothi-Jimit commented 5 years ago

hmm if you got solution let me know. or i got solution i will tell you :)

Thank you for support.

Hothi-Jimit commented 5 years ago

issue resolve. write just else condition.

protected function join_temporary_results($data)
    {
        foreach($this->_requested as $requested_key => $request)
        {
            $order_by = array();
            $order_inside_array = array();
            $pivot_table = NULL;
            $relation = $this->_relationships[$request['request']];
            $this->load->model($relation['foreign_model'],$relation['foreign_model_name']);
            $foreign_key = $relation['foreign_key'];
            $local_key = $relation['local_key'];
            $foreign_table = $relation['foreign_table'];
            $type = $relation['relation'];
            $relation_key = $relation['relation_key'];
            if($type=='has_many_pivot')
            {
                $pivot_table = $relation['pivot_table'];
                $pivot_local_key = $relation['pivot_local_key'];
                $pivot_foreign_key = $relation['pivot_foreign_key'];
                $get_relate = $relation['get_relate'];
            }
            if(array_key_exists('order_inside',$request['parameters']))
            {
                //$order_inside = $request['parameters']['order_inside'];
                $elements = explode(',', $request['parameters']['order_inside']);
                foreach($elements as $element)
                {
                    $order = explode(' ',$element);
                    if(sizeof($order)==2)
                    {
                        $order_inside_array[] = array(trim($order[0]), trim($order[1]));
                    }
                    else
                    {
                        $order_inside_array[] = array(trim($order[0]), 'desc');
                    }
                }
            }
            $local_key_values = array();
            foreach($data as $key => $element)
            {
                if(isset($element[$local_key]) and !empty($element[$local_key]))
                {
                    $id = $element[$local_key];
                    $local_key_values[$key] = $id;
                }
            }
            if(!$local_key_values)
            {
                $data[$key][$relation_key] = NULL;
                continue;
            }
            if(!isset($pivot_table))
            {
                $sub_results = $this->{$relation['foreign_model_name']};
                $select = array();
                $select[] = '`'.$foreign_table.'`.`'.$foreign_key.'`';
                if(!empty($request['parameters']))
                {
                    if(array_key_exists('fields',$request['parameters']))
                    {
                        if($request['parameters']['fields'] == '*count*')
                        {
                            $the_select = '*count*';
                            $sub_results = (isset($the_select)) ? $sub_results->fields($the_select) : $sub_results;
                            $sub_results = $sub_results->fields($foreign_key);
                        }
                        else
                        {
                            $fields = explode(',', $request['parameters']['fields']);
                            foreach ($fields as $field)
                            {
                                $select[] = (strpos($field,'.')===FALSE) ? '`' . $foreign_table . '`.`' . trim($field) . '`' : trim($field);
                            }
                            $the_select = implode(',', $select);
                            $sub_results = (isset($the_select)) ? $sub_results->fields($the_select) : $sub_results;
                        }
                    }
                    if(array_key_exists('fields',$request['parameters']) && ($request['parameters']['fields']=='*count*'))
                    {
                        $sub_results->group_by('`' . $foreign_table . '`.`' . $foreign_key . '`');
                    }
                    if(array_key_exists('where',$request['parameters']) || array_key_exists('non_exclusive_where',$request['parameters']))
                    {
                        $the_where = array_key_exists('where', $request['parameters']) ? 'where' : 'non_exclusive_where';
                    }
                    $sub_results = isset($the_where) ? $sub_results->where($request['parameters'][$the_where],NULL,NULL,FALSE,FALSE,TRUE) : $sub_results;
                    if(isset($order_inside_array))
                    {
                        foreach($order_inside_array as $order_by_inside)
                        {
                            $sub_results = $sub_results->order_by($order_by_inside[0],$order_by_inside[1]);
                        }
                    }
                    //Add nested relation
                    if(array_key_exists('with',$request['parameters']))
                    {
                        // Do we have many nested relation
                        if(is_array($request['parameters']['with']) && isset($request['parameters']['with'][0])&& is_array($request['parameters']['with'][0]))
                        {
                            foreach ($request['parameters']['with'] as $with)
                            {
                                $with_relation = array_shift($with);
                                $sub_results->with($with_relation, array($with));
                            }
                        }
                        else // single nested relation
                        {
                            $with_relation = array_shift($request['parameters']['with']);
                            $sub_results->with($with_relation,array($request['parameters']['with']));
                        }
                    }
                }
                $sub_results = $sub_results->where($foreign_key, $local_key_values)->get_all();
            }
            else
            {
                $this->_database->join($pivot_table, $foreign_table.'.'.$foreign_key.' = '.$pivot_table.'.'.$pivot_foreign_key, 'left');
                $this->_database->join($this->table, $pivot_table.'.'.$pivot_local_key.' = '.$this->table.'.'.$local_key,'left');
                $this->_database->select($foreign_table.'.'.$foreign_key);
                $this->_database->select($pivot_table.'.'.$pivot_local_key);
                if(!empty($request['parameters']))
                {
                    if(array_key_exists('fields',$request['parameters']))
                    {
                        if($request['parameters']['fields'] == '*count*')
                        {
                            $this->_database->select('COUNT(`'.$foreign_table.'`.`'.$foreign_key.'`) as counted_rows, `' . $foreign_table . '`.`' . $foreign_key . '`', FALSE);
                        }
                        else
                        {
                            $fields = explode(',', $request['parameters']['fields']);
                            $select = array();
                            foreach ($fields as $field) {
                                $select[] = (strpos($field,'.')===FALSE) ? '`' . $foreign_table . '`.`' . trim($field) . '`' : trim($field);
                            }
                            $the_select = implode(',', $select);
                            $this->_database->select($the_select);
                        }
                    }
                    if(array_key_exists('where',$request['parameters']) || array_key_exists('non_exclusive_where',$request['parameters']))
                    {
                        $the_where = array_key_exists('where',$request['parameters']) ? 'where' : 'non_exclusive_where';
                        $this->_database->where($request['parameters'][$the_where],NULL,NULL,FALSE,FALSE,TRUE);
                    }
                }
                $this->_database->where_in($pivot_table.'.'.$pivot_local_key,$local_key_values);
                if(!empty($order_inside_array))
                {
                    $order_inside_str = '';
                    foreach($order_inside_array as $order_by_inside)
                    {
                        $order_inside_str .= (strpos($order_by_inside[0],'.')=== false) ? '`'.$foreign_table.'`.`'.$order_by_inside[0].' '.$order_by_inside[1] : $order_by_inside[0].' '.$order_by_inside[1];
                        $order_inside_str .= ',';
                    }
                    $order_inside_str = rtrim($order_inside_str, ",");
                    $this->_database->order_by($order_inside_str);
                }
                $sub_results = $this->_database->get($foreign_table)->result_array();
                $this->_database->reset_query();
            }
            if(isset($sub_results) && !empty($sub_results)) {
                $subs = array();
                foreach ($sub_results as $result) {
                    $result_array = (array)$result;
                    $the_foreign_key = $result_array[$foreign_key];
                    if(isset($pivot_table))
                    {
                        $the_local_key = $result_array[$pivot_local_key];
                        if(isset($get_relate) and $get_relate === TRUE)
                        {
                            $subs[$the_local_key][$the_foreign_key] = $this->{$relation['foreign_model']}->where($foreign_key, $result[$foreign_key])->get();
                        }
                        else
                        {
                            $subs[$the_local_key][$the_foreign_key] = $result;
                        }
                    }
                    else
                    {
                        if ($type == 'has_one') {
                            $subs[$the_foreign_key] = $result;
                        } else {
                            $subs[$the_foreign_key][] = $result;
                        }
                    }
                }
                $sub_results = $subs;
                foreach($local_key_values as $key => $value)
                {
                    if(array_key_exists($value,$sub_results))
                    {
                        $data[$key][$relation_key] = $sub_results[$value];
                    }
                    else
                    {
                        if(array_key_exists('where',$request['parameters']))
                        {
                            unset($data[$key]);
                        }else{
                            // If Result not find then blank return.
                            // Note If you want then add otherwise no need add.
                            $data [$key] [$relation_key]=array();
                        }
                    }
                }
            }
            else
            {
                $data[$key][$relation_key] = NULL;
            }
            if(array_key_exists('order_by',$request['parameters']))
            {
                $elements = explode(',', $request['parameters']['order_by']);
                if(sizeof($elements)==2)
                {
                    $order_by[$relation_key] = array(trim($elements[0]), trim($elements[1]));
                }
                else
                {
                    $order_by[$relation_key] = array(trim($elements[0]), 'desc');
                }
            }
            unset($this->_requested[$requested_key]);
        }
        if(!empty($order_by))
        {
            foreach($order_by as $field => $row)
            {
                list($key, $value) = $row;
                $data = $this->_build_sorter($data, $field, $key, $value);
            }
        }
        return $data;
    }

$data [$key] [$relation_key]=array(); add this line if you need blank.