Resembling table field as some alias in Codeigniter - codeigniter

In codeigniter i am creating a general function for some data insertion
for it i am keeping some norms
say i have two tables one being dt_category and the other being dt_product
here's the dt_category struture
|-------------------|---------------------|--------------------|------------------|
| category_id | category_name | category_slug | timestamp |
|-------------------|---------------------|--------------------|------------------|
and here's the dt_product structure
|-------------------|---------------------|--------------------|------------------|
| product_id | product_name | product_slug | timestamp |
|-------------------|---------------------|--------------------|------------------|
as u can see, both the tables fields just change by the field-name prefix, i mean in dt_category its category_id
and in dt_product its product_id and so on
now while calling the function to insert category data i use this method
$category_name=$this->input->post('category_name');
$insert_array=array('category_name'=>$category_name,
'timestamp'=>time());
$data['msg']=$this->erp_model->data_insert('dt_category',$insert_array);
and for product data
just this method
$product_name=$this->input->post('product_name');
$insert_array=array('product_name'=>$product_name,
'timestamp'=>time());
$data['msg']=$this->erp_model->data_insert('dt_product',$insert_array);
the function that deals with the insertion is this one
function data_insert($table,$data)
{
$this->db->insert($table,$data);
$timestamp=$data['timestamp'];
$table_nm=explode('_',$table); //spliting the table name in format dt_table_name,
$table_slug=$table_nm[1]."_"."slug";//if its dt_product table_nm[1]="product",
//if category,table_nm[1]="category"
//thus $table_slug="product_slug" or "category_slug"
$query = $this->db->select('*')
->from($table)
->where('timestamp', $timestamp)
->get();
foreach($query->result() as $r_q)
{
$id=$r_q->$table_nm[1].'_id';//i want $id value of product_id since $table_nm[1]="product"
$name=$r_q->$table_nm[1].'_name';//i want $name value of product_name since $table_nm[1]="product"
}
echo $id."-".$name;
}
in the aboce function based on the table_name
i want to fetch the value of field name
$id=$r_q->$table_nm[1].'_id'; should resemble $id=$r_q->product_id; if the table is dt_product
i know i am doing the wrong way, because ->product_id is a resultanat object while i am trying to expressing as a string,
is there a way of how i can achieve the thing,
i mean fetching the field name based on the table name;

Ok, i solved my problem, and here's the answer
i was trying the concatenation at the time of retrieval,
but now i did it first and then assigned the field
$tab_id=$table_nm[1].'_id';
$tab_name=$table_nm[1].'_name';
here's the resolved code
function data_insert($table,$data)
{
$this->db->insert($table,$data);
$timestamp=$data['timestamp'];
$table_nm=explode('_',$table);
$table_slug=$table_nm[1]."_"."slug";
echo $table_slug;
$query = $this->db->select('*')
->from($table)
->where('timestamp', $timestamp)
->get();
$tab_id=$table_nm[1].'_id';
$tab_name=$table_nm[1].'_name';
foreach($query->result() as $r_q)
{
$id=$r_q->$tab_id;
$name=$r_q->$tab_name;
}
echo $id."-".$name;
}

Related

In Laravel I'm attempting to get the info from a table with a pivot

I currently have 3 tables:
medias, colors, media_colors
media_colors is the pivot table I'm trying to use it contains
media_id | color_id
------------------
1 | 1
in colors table I have
id | front
----------
1 | color
My model for medias contains:
public function mediaColors()
{
return $this->belongsToMany(Color::class, 'media_colors');
}
In a controller I attempt to query front like so:
$m = Media::find($estimate->media_id);
dd($m->mediaColors[0]->pivot->front);
This returns null. How would I be able to access this?
You can access the colors directly from the relation collection as marked in the comment.
$m = Media::find($estimate->media_id);
foreach($m->mediaColors as $color) {
//you can access all the colors here
$fronts[] = $color->front;
}
//or if you only want the first one (if it exists)
$m->mediaColors[0]->front
one easier way to get just the first value if you only need that
$m = Media::find($estimate->media_id);
$front = $m->mediaColors()->value('front');
// this will return null if no relation found without triggering an exception

Eloquent query with a RAW order by

I have a eloquent query to get list items.
This is based on the idea that the sort column would be filled in, but in some circumstances it is not.
If its the case then I would like to order by the name of the list.
More or less what I wrote bellow.
order by CASE WHEN trickysort IS NOT NULL THEN trickysort::text ELSE list_name END
Here is the original query.
$list = Table_Lists::with(["listItems" =>
function($query)
{
$query
->orderBy('trickysort', 'asc')
->with("sublist.listItems");
}
])
->where("list_name","=", $name)
->where("hos_id","=", $hos_id)->get()->first();
return $list ? $list->toArray() : null;
The table structure is as follows.
Parent table -> table_lists
related child table -> table_list_items
the child table items are the one I need sorting. ( trickysort else list_name )
I hope this makes sense.
Im was thinking kind of a RAW query bit in the ->orderBy section of the child table.

Codeigniter active record query with concat as join parameter

I currently have 2 tables in which I need to get data from.
My users table looks like:
ID | first_name | last_name | username
My data table looks like:
ID | filename | doctorname | viewed
What I need to do match the first name and last name from the users table to the doctor name in the data table and the return the "filename" and "viewed" rows from this.
I can't seem to get the query right for it though. I'm using the active record class with code igniter. Ive also tried to have a separate function that concats the first and last name and returns it but I can't seem to pass that variable to the join section of the query.
$avail = '1';
$this->db->select('*');
$this->db->from("users a");
$this->db->where("username",$username);
$this->db->where('CONCAT(first_name, '.', last_name) AS doctorname', FALSE);
$this->db->join('data b', "doctor name = b.doctorName", "left");
$result = $this->db->get();
// print_r($this->db->last_query());
return $result->result();
Anyone know whats going wrong?
Thanks
Try like this
$avail = '1';
$this->db->select('a.*,b.filename,b.viewed');
$this->db->from("users as a");
$this->db->join('data as b', "CONCAT(a.first_name, '.', a.last_name) = b.doctorName", "left");
$this->db->where("a.username",$username);
$result = $this->db->get();
// print_r($this->db->last_query());
return $result->result();

Laravel 4.2 HasMany Relationship using Like

I'm wondering if its possible to set the operator when using a HasMany relationship in Laravel 4.2.
I'm working with a users table and an email log table. The log table has a userID stored in serialised format (as there may be more than one userID stored within the log).
Users table
+---------+
| user_ID |
+---------+
| 1 |
| 2 |
+---------+
emailLog Table
+----+--------------------+
| ID | user_ID |
+----+--------------------+
| 1 | a:1:{i:0;s:1:"2";} |
| 2 | a:1:{i:0;s:1:"1";} |
+----+--------------------+
Am I able to use a hasMany relation with a 'Like' operator rather than an equals operator to return the correct email log ID? Would the statement be written something like the below?
return $this->hasMany('emailLog', 'user_ID', '%user_ID%', 'LIKE');
The proper way to return join table with a where clause would be:
return $this->hasMany('emailLog','user_id')->where('user_id', 'LIKE', '%user_id%');
I found a way to do something similar
class User extends Model
{
public function emailLogs()
{
// old code
// return $this->hasMany(EmailLogs::class, 'user_ID');
// Replace HasMany by like query
return EmailLogs::where('user_ID', 'LIKE', "%{$this->user_ID}%");
}
}

Get values from a doctrine collection with composite key

4 for on on my applications with Doctrine.
In there I'm using the following doctrine command to retrieve person object collection
//query
$people = $q->execute();
This return 20 objects. The primary key of the person object is a composite key with three attributes. Those are
id
department_id
name
I need to get person objects by searching in it as follows.
$id = 10;
$department_id = 1;
$name = "abc";
$people->get($id, $department_id, $name);
But this doesn't work and not give correct results. I tried with this and it gives null results which seems my collections primary key is not set.
$people->getKeyColumn();
I don't want to go through a foreach loop in collection and process it because when I deal with about 500 people, it slow down my application.
Can some one help me with this issue to get values from a doctrine collection.
Can you use something like this?
$people = Doctrine::getTable('Persons')
->createQuery()
->where('id = ? AND department_id = ? AND name = ?', array($id, $department_id, $name))
->execute();
It will get you a DoctrineCollection already filtered by the parameters provided.
'Persons' here is a Doctrine model name, not a table name from mySQL.
You can also use Doctrine's magic finders findBy*():
$people = Doctrine_Core::getTable('Persons')
->findByIdAndDepartmentIdAndName($id, $department_id, $name);

Resources