Cannot use object of type stdClass as an array in codeigniter - codeigniter

My controller code
function edtpost($id)
{
$this->load->model('post');
$data = $this->post->edt_post($id);
$this->load->model('category');
$data['catname'] = $this->category->retrivecat();
$this->load->view('dashboard/edit_post',$data);
}
my model code
model post
public function edt_post($id)
{
$query = $this->db->get_where('post', array('id' => $id));
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
return $row;
}
}
return false;
}
category model
public function retrivecat()
{
$query = $this->db->get('category');
foreach ($query->result() as $row)
{
$data[] = $row->catname;
}
return $data;
}
in controller & this code $data['catname'] = $this->category->retrivecat();
I have one error:
Cannot use object of type stdClass as array

Just change your that line with following :-
$data->catname = $this->category->retrivecat();

Related

error while update method on boolean

I am trying to update method in Laravel but error is:
"Call to a member function tradereason() on boolean"
I also check same question of other people asked but there're a lot of different in my process. I have lot tables.
let me show you my create code and update method coding.
Create method code:
public function store(Request $request)
{
$tradeID= Auth::user()->trade()->create($input);
$input = $request->all();
$reasons = $request->input('reason');
//Loop for creating KEY as Value
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->save(new TradeReason($datum));
}
}
}
this is my tring code for update method:
public function update(Request $request, $id)
{
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
$input = $request->all();
$reasons = TradeReason::whereId($id)->first();
$reasons->update($input);
$reasons->tradereason()->sync($request->input('reason'));
$data = [];
foreach($reasons as $key => $value) {
$data[] = ['reason_id' => $value];
};
if( $data > 0 ) {
foreach ($data as $datum) {
$tradeID->tradereason()->whereId($id)->first()->update($datum);
}
}
}
update returns a boolean. So, don't overwrite $tradeID with the results of update.
$tradeID = Auth::user()->trade()->whereId($id)->first();
$tradeID->update($input);
Calling update on the Builder returns an 'int'. Calling update on the Model returns a 'bool'. They don't return Model instances.
// bool
$tradeID= Auth::user()->trade()->whereId($id)->first()->update($input);
The model instance would be what is returned from the first call:
$tradeID = Auth::user()->trade()->whereId($id)->first(); // assuming it finds a record
You can update that, you can use it in the foreach loop.

Laravel belongsTo with condition and eager load

I have a Post model associated to a Section model, which depend on an extra condition to work:
<?php
class Post extends Base
{
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat')->where('website', $this->website);
}
}
When I want to retrieve a Post and get it's associated section, I can do it as:
$post = Post::first();
echo $post->section->name; // Output the section's name
However, when trying to get the section using an eager load:
Post::with(['section'])->chunk(1000, function ($posts) {
echo $post->section->name;
});
Laravel throw the following exception :
PHP error: Trying to get property of non-object
When I do a debug of a Post object returned by the above eager load query, I notice that the section relationship is null.
Note that it is working fine if I remove the condition from the belongsTo association.
Do you guys have any ideas why it's happening?
As mentioned in my comment, where shouldn't be used in the relationship definition. Hence, your relation definition is good with just
public function section()
{
return $this->belongsTo('App\Models\Section', 'id_cat');
}
and you can eager load in this way (not giving out the exact query with chunk etc)
Post::with(['section' => function ($query) use ($request) {
$query->where('website', $request['website'])
}])->get()->first();
i.e. when you pass the variable website in request or else use any other variable in a similar way.
I hope that explains. Please add comments if anything is unclear.
You can achieve it by defining custom relationship.
BelongsToWith.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BelongsToWith extends BelongsTo
{
/**
* #var array [$foreignColumn => $ownerColumn, ...] assoc or [$column, ...] array
*/
protected $conditions = [];
public function __construct(array $conditions, Builder $query, Model $child, string $foreignKey, string $ownerKey, string $relation)
{
$this->conditions = $conditions;
parent::__construct($query, $child, $foreignKey, $ownerKey, $relation);
}
public function addConstraints()
{
if (static::$constraints) {
// Add base constraints
parent::addConstraints();
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$this->getQuery()->where($this->related->getTable() . '.' . $value, '=', $this->child->{$key});
}
}
}
public function addEagerConstraints(array $models)
{
// Ignore empty models
if ([null] === $this->getEagerModelKeys($models)) {
parent::addEagerConstraints($models);
return;
}
$this->getQuery()->where(function (Builder $query) use ($models) {
foreach ($models as $model) {
$query->orWhere(function (Builder $query) use ($model) {
// Add base constraints
$query->where($this->related->getTable() . '.' . $this->ownerKey, $model->getAttribute($this->foreignKey));
// Add extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
$query->where($this->related->getTable() . '.' . $value, $model->getAttribute($key));
}
});
}
});
}
public function match(array $models, Collection $results, $relation)
{
$dictionary = [];
foreach ($results as $result) {
// Base constraints
$keys = [$result->getAttribute($this->ownerKey)];
// Extra constraints
foreach ($this->conditions as $key => $value) {
$keys[] = $result->getAttribute($value);
}
// Build nested dictionary
$current = &$dictionary;
foreach ($keys as $key) {
$current = &$current[$key];
}
$current = $result;
unset($current);
}
foreach ($models as $model) {
$current = $dictionary;
// Base constraints
if (!isset($current[$model->{$this->foreignKey}])) {
continue;
}
$current = $current[$model->{$this->foreignKey}];
// Extra constraints
foreach ($this->conditions as $key => $value) {
if (is_int($key)) {
$key = $value;
}
if (!isset($current[$model->{$key}])) {
continue 2;
}
$current = $current[$model->{$key}];
}
// Set passed result
$model->setRelation($relation, $current);
}
return $models;
}
}
HasExtendedRelationships.php
<?php
declare(strict_types=1);
namespace App\Database\Eloquent\Concerns;
use App\Database\Eloquent\Relations\BelongsToWith;
use Illuminate\Support\Str;
trait HasExtendedRelationships
{
public function belongsToWith(array $conditions, $related, $foreignKey = null, $ownerKey = null, $relation = null): BelongsToWith
{
if ($relation === null) {
$relation = $this->guessBelongsToRelation();
}
$instance = $this->newRelatedInstance($related);
if ($foreignKey === null) {
$foreignKey = Str::snake($relation) . '_' . $instance->getKeyName();
}
$ownerKey = $ownerKey ?: $instance->getKeyName();
return new BelongsToWith($conditions, $instance->newQuery(), $this, $foreignKey, $ownerKey, $relation);
}
}
Then:
class Post extends Base
{
use HasExtendedRelationships;
public function section(): BelongsToWith
{
return $this->belongsToWith(['website'], App\Models\Section::class, 'id_cat');
}
}
$posts = Post::with('section')->find([1, 2]);
Your Eager Loading query will be like:
select * from `sections`
where (
(
`sections`.`id` = {$posts[0]->id_cat}
and `sections`.`website` = {$posts[0]->website}
)
or
(
`sections`.`id` = {$posts[1]->id_cat}
and `sections`.`website` = {$posts[1]->website}
)
)

getting error while passing a array through loop

This my controller function
public function update_monthly() {
$data = $this->student_model->get_due_info();
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value);
$grade = $this->student_model->get_grade_by_id($value);
$grade_due = $this->student_model->get_due_by_grade($grade);
$new_due = $due + $grade_due;
$this->db->set('md_due',$new_due, FALSE);
}
}
I am getting following error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_active_rec.php
Line Number: 427
and
A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT `md_due` FROM (`monthly_due`) WHERE `md_student_id` = Array
Filename: F:\xampp\htdocs\student\system\database\DB_driver.php
Line Number: 330
Model Code
public function get_due_by_id($id) {
$this->db->select('md_due');
$this->db->from('monthly_due');
$this->db->where('md_student_id', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_due_by_grade($id) {
$this->db->select('dt_fee');
$this->db->from('due_table');
$this->db->where('dt_grade', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_grade_by_id($id) {
$this->db->select('grade');
$this->db->from('student_info');
$this->db->where('student_gen_id', $id);
$query = $this->db->get();
return $query->result_array();
}
public function get_due_info() {
$this->db->select('md_student_id');
$this->db->from('monthly_due');
$query = $this->db->get();
return $query->result_array();
}
Pass $value['md_student_id'] to the model instead of $value in controller.
$data = $this->student_model->get_due_info();
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value['md_student_id'] );
$grade = $this->student_model->get_grade_by_id($value['md_student_id']);
$grade_due = $this->student_model->get_due_by_grade($grade[0]['grade']);
//Add remaining logic
}
you are passing whole the array to your model not just the value you want
$due = $this->student_model->get_due_by_id($value);
the right thing is to pass
$value['md_student_id']
this is the value you actually want to pass
replace your code with this
foreach ($data as $value) {
$due = $this->student_model->get_due_by_id($value['md_student_id'] );
$grade = $this->student_model->get_grade_by_id($value['md_student_id']);
$grade_due = $this->student_model->get_due_by_grade($grade[0]['grade']);
$new_due = $due + $grade_due;
$this->db->set('md_due',$new_due, FALSE);
}

select fails in custom model codeigniter 2

I have a problem with database select function, in my custom model. This is the code
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('inflector');
}
public function fetch($parameters = array(), $raw = FALSE)
{
$tablename = $this->getTableName();
$this->select_fields(FALSE == empty($parameters['fields']) ? $parameters['fields'] : FALSE);
unset($parameters['fields']);
if (FALSE == empty($parameters['limit'])) $limit = $parameters['limit'];
if (FALSE == empty($parameters['offset'])) $offset = $parameters['offset']; else $offset = 0;
unset($parameters['limit']);
unset($parameters['offset']);
if (FALSE == empty($limit))
{
$this->db->limit($limit, $offset);
}
$this->parseFilters($parameters);
$query = $this->db->get($tablename);
if ($query->num_rows() > 0)
{
if ($raw)
return $query;
$rows = $query->result();
$objects = array();
foreach ($rows as $row)
$objects[] = $this->hidrate($row);
return $objects;
}
else
{
return array();
}
}
protected function select_fields($fields)
{
if (TRUE == empty($fields))
{
$fields = "`" . $this->getTableName() . "`.*";
}
$this->db->select($fields);
}
public function fetchOne($parameters = array())
{
$parameters['limit'] = 1;
$list = $this->fetch($parameters);
if (FALSE == empty($list))
{
return reset($list);
}
else
{
return null;
}
}
Expecifict in $this->db->select($fields);
Fatal error: Call to a member function select() on a non-object
The model is a custom model and the applicacions model extends of this model. The question is why throws that error the database is correct.
I have a MY_loader create in codeginiter 1.7 and I try update to codeigniter 2
class MY_Loader extends CI_Loader
{
function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
if ( substr($model, -4) == '_dao' )
{
return parent::model('dao/' . $model, $name, $db_conn);
}
parent::model( 'dao/' . $model . '_dao', $model, $db_conn);
include_once APPPATH . '/models/' . $model . EXT;
}
}
I don't know how update this model to codeigniter 2 and I believe this Loader generates error with my MY_Model
I'll try troubleshooting why does db return as a non-object.
I'd remove all code and start with a simple select(), if that works, I'll start adding code gradually and see where it breaks.
everything seems to be in order but first you'll need to see if the basic functionality exists.
so
1)remove all code, see if a basic select() works, if it doesn't, troubleshoot further.
2)if it does, keep adding code and see what breaks the select() statement.
3)keep adding code until you spot the issue.

Why am getting error like this in view page

CI_DB_mysql_result Object([conn_id] => Resource id #28[result_id] => Resource id #33[result_array] => Array ()[result_object] => Array()[custom_result_object] => Array()
[current_row] => 0 [num_rows] => 1[row_data] =>)
here is my model page
public function getProductsListByCategory1($limit, $start)
{
$this->db->limit($limit, $start);
$this->db->select('image_path,tagline,category_id,product_id');
$this->db->where('category_id','1');
$query = $this->db->get("tb1_bl_products order by tagline");
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
else
{
return array();
}
}
use $query->result_array() rather than $query->result()

Resources