I have the following query:
$result = Table1::model()->findAll(array(
'with' => array(
'table2' => array(
'joinType' => 'LEFT JOIN',
'on' => 'pk = fk AND fk=1'
)
),
'select' => array('name',
'COALESCE(table2.price, t.standardprice) AS price',
'COALESCE(table2.period, t.period) AS period')
)
);
My goal is to pick table2's fields if those are filled in, but if these are empty / no rows found the original table's fields should be displayed.
However, my output isn't as expected. The price field isn't displayed at all in my result's attributes, and the period field is either table2's value or empty.
EDIT: Perhaps my SQL is wrong somewhere. Using this SQL gives me the wanted results:
SELECT name, COALESCE(tb1.price, tb2.standardprice) as price, COALESCE(tb1.period, tb2.period) as period
FROM table1 as tb1
LEFT JOIN table2 as tb2
ON (tb1.pk= tb2.fk) AND fk=1;
Yet I don't see any difference with my current code.
EDIT2: Table structures:
Table1 (original table)
pk (int 11) - Primary key, auto increment
name (varchar 255)
standardprice (decimal 11,2)
period (varchar 255)
fkLanguage //not relevant
photo //not relevant
description //not relevant
link //not relevant
Table2
ID (int 11) - Primary key, auto increment
fk (int 11) - Foreign key, which links to pk of table1
period (varchar 255)
price (decimal 11,2)
fkType //not relevant
amount //not relevant
Clarification: The fk=1 is indeed a JOIN condition. If the fk isn't 1 then I don't want those rows to join, but take the values from table1 instead.
You need to add column price for parsing not existing column in schema.
Try to modify model Table1 ()
add public $price;
override method attributeNames to following:
public function attributeNames()
{
$colums = parent::attributeNames();
$colums[] = 'price';
return $colums;
}
I think you should do like this:
$result = Tablename::model()->findAll(array(
'with' => array(
'tabel2' => array(
'joinType' => 'LEFT JOIN',
'on' => 'pk = fk'
)
),
'select' => array('name',
'COALESCE(tabel2.price, t.standardprice) AS price',
'COALESCE(tabel2.period, t.period) AS period'),
'condition'=> ' fk = 1 '
));
because fk = 1 is not a part of the on statement; it is only a condition. I think that will make the difference for you.
Related
I need to populate my database column from seeding. I have 'interested_in' column in user_profiles table and I need to populate it with according id from 'value_id' column from user_interests table. Both user_profiles and user_interests table are connected to users table ('user_id' column is in both tables). So if the value of 'value_id' column is for example 1 it needs to be 1 in 'interested_in' column, I need help on how to populate that 'interested_in' column from seeders. 'value_id' column is already populated. Here are my tables and example data and my code so far but it doesn't work currently, it shows 'Array to string conversion' error.
user_interests table
user_id field_id value_id
1 1 1
user_profiles table
id user_id interested_in
1 1 and here needs to be 1, to associate value_id (1) from user_interests table
UserProfileTableSeeder.php
class UserProfileTableSeeder extends Seeder
{
use ChunkSeeder;
public function run()
{
$users = User::all()->pluck('id');
$user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 1)->get();
$user_interests_values = $user_interests->pluck('value_id')->toArray();
$seed = [];
foreach ($users as $userId) {
$seed[] = factory(UserProfile::class)->make(
[
'user_id' => $userId,
'interested_in' => $user_interests_values, // Shows array to string error!!!
]
)->toArray();
}
$this->seedChunks($seed, [UserProfile::class, 'insert']);
}
}
That's why $user_interests_values is an array as you can see in this line (at the end):
$user_interests_values = $user_interests->pluck('value_id')->toArray();
Try in the factory to change $user_interests_values to current($user_interests_values) or probably $user_interests_values['id'] or whatever.
PS: I am not really sure what's inside $user_interests_values, you can see it with a dd() and running the migration then (don't worry, the migration won't be successful because of the dd() and you will be able to run it later again until it finishes properly.
By the way, I recommend you to do something more legible than you did in your rum() method. I mean, something like this:
$interest = factory(UserInterests::class)->create();
factory(UserProfiles::class, 20)->create([
'interest' => $interest->id,
]);
My controller query is as below :
$built_arr = $this->User->query("SELECT u1.id,
CASE WHEN u1.role = 'CW' THEN u2.agency_name
WHEN u3.role = 'EU' THEN u2.agency_name ELSE u1.agency_name END AS agency
FROM users u1 LEFT JOIN users u2 ON (u1.parent = u2.id AND u2.role = 'A')
LEFT JOIN users u3 ON (u1.id = u3.parent AND u1.role = 'CW')
LEFT JOIN users u4 ON (u1.parent = u4.id AND u4.role = 'A')
WHERE u1.role = 'A' OR u1.role = 'CW'
GROUP BY u1.id");
And My code of array from this query is as below :
if (isset($built_arr) && !empty($built_arr)) {
foreach ($built_arr AS $key => $value) {
if (isset($value[0]['agency']) && !empty($value[0]['agency'])) {
$agency_arr[$value['u1']['id']] = $value[0]['agency'];
}
}
}
Now I have set this data to view like as below :
$this->set('agency_arr', $agency_arr);
Now this Array (agency_arr), I have used as data of columns of a table in view page.
Now I want to sort that column with this array data.
My view code as below :
<th><?php echo $this->Paginator->sort('?', __("Agency Name"), array('escape' => false)); ?></th>
Advice for the "?" sign.
What I have to write instead of "?", So I can sort with my array data.
My other column's data come from the paginate query so those are working fine.
I need this extra query for extra column, so need to sort by that column.
To the sort question:
Cake\View\Helper\PaginatorHelper::sort($key, $title = null, $options =[])
Parameters:
$key (string) – The name of the column that the recordset should be sorted.
$title (string) – Title for the link. If $title is null $key will be used for the title and will be generated by inflection.
$options (array) – Options for sorting link.
So i guess this is what you want: $paginator->sort('agency_name', 'Agency Name', array('escape' => false));
I would suggest to set up associations properly if you didnt already and use a find call with contains.
Since there are parents i guess its a HasAndBelongsToMany relation. (Children have multiple parents and parents multiple children)
CREATE TABLE `users` (
user_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
role varchar(255),
);
CREATE TABLE `childrens_parents` (
childrens_parents_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
parent_id int,
children_id int,
FOREIGN KEY (u1_id) REFERENCES users(user_id),
FOREIGN KEY (u2_id) REFERENCES users(user_id)
);
In your Model/UsersTable set up the association properly like described in
the cakephp book
(dont forget targetforeignkey+foreignkey)
Now you can do something like this:
$query = $this->Users->find()->where(['role'=>'A'])->orWhere(['role'=>'CW'])->contain([
'Children' => function ($q) {
return $q
->where(['Role =' => 'CW']);
}
])->contain([
'Parents' => function ($q) {
return $q
->where(['Role =' => 'A']);
}
])->group('user_id');
Now you can paginate over the resultset accessing all fields of the objects.
foreach($query as $row) {
debug($row);//see how nicely the resultarray is looking
echo($row->Parents[0]->user-id);// access related Entities
}
If its not HABTM but hasMany or some other type you can adapt it easily.
And I strongly recommend on holding in cake conventions !
Ressources (I recommend on reading the whole articles for proper cakephp work):
http://book.cakephp.org/3.0/en/orm/query-builder.html
http://book.cakephp.org/3.0/en/orm/associations.html
I have a table with three fields
id (primary key / auto incremented)
product_name
group_id
my problem is when i insert multiple rows through form the whole group of rows should get same groupId & it should be incremented by 1 at the time of submission as there can be many users submitting the form at the same time. I dont know how to do it. Please help.
my model
function get_last_group_id() {
$this->db->select('group_id');
$this->db->from('mytable');
$this->db->order_by('group_id', 'DESC');
$this->db->limit('1');
$query = $this->db->get();
return $query->result();
}
function save_rows($ids,$product_names,$group_ids){
$this->db->trans_begin();
$ndx=0;
foreach($ids as $id){
$data = array(
'id' => $id,
'product_name' => $product_names[$ndx],
'group_id' =>$group_ids[$ndx],
$this->db->insert("product_details",$data);
$this->db->update($this->table);
$ndx++;
}
There is no need to make seperate function for getting group id and set id field also if that is auto incre
function save_rows($ids,$product_names){
$this->db->trans_begin();
$ndx=0;
$group_id = $this->db->select("MAX(group_id) as group_id")
->from("mytable")
->get()->row_array();
foreach($ids as $id){
$data = array(
'product_name' => $product_names[$ndx],
'group_id' =>$group_id['group_id']+1,
);
$this->db->insert("product_details",$data);
$ndx++;
}
You can create a new table say 'groups'
fields: id(Auto Increment) and group_name (varchar)
generate group name randomly.
Then before inserting products create a new group then you will get a new groupID that will be unique.
Then using that groupID you can carry your option forward
I cannot get primary id array, I try to debug it happens when use joinLeft function
Here my script
//setIntegrityCheck to false to allow joins
$roomModel = new self();
$select = $roomModel->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
->setIntegrityCheck(FALSE);
//performs join aliasing table room_type to t
$select->join(array('t' => 'room_types'), 't.room_type_id = rooms.room_type_id AND num_beds> '.$number_beds);
////performs join aliasing table room_status to s
$select->join(array('s' => 'room_statuses'), 's.room_status_id = rooms.room_status_id');
$select->joinLeft(array('chin' => 'checkin'), 'chin.checkin_date > '.$checkin.' AND chin.checkin_date <'.$checkout.'');
$select->joinLeft(array('chout' => 'checkout'), 'chout.checkout_date >'.$checkin.' AND chout.checkout_date <'.$checkout.'');
$result = $roomModel->fetchAll($select);
What causes it to happen?
one of the tables you are joining also may contain a column named like your primary key and if the row does not exist it will override it with null.
you should choose which columns you want from each table:
$select->join('table', 'condition', array('column1', 'column2', 'column3'));
$select->joinLeft('table', 'condition', array('column1', 'column2', 'column3'));
I am trying to use ORM to access data stored, in three mysql tables 'users', 'items', and a pivot table for the many-many relationship: 'user_item'
I followed the guidance from Kohana 3.0.x ORM: Read additional columns in pivot tables
and tried
$user = ORM::factory('user',1);
$user->items->find_all();
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
if ($user_item->loaded()) {
foreach ($user_item as $pivot) {
print_r($pivot);
}
}
But I get the SQL error:
"Unknown column 'user_item.id' in
'order clause' [ SELECT user_item.*
FROM user_item WHERE user_id = '1'
AND item_id = '' ORDER BY
user_item.id ASC LIMIT 1 ]"
Which is clearly erroneous because Kohana is trying to order the elements by a column which doesn't exist: user_item.id. This id doesnt exist because the primary keys of this pivot table are the foreign keys of the two other tables, 'users' and 'items'.
Trying to use:
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items))
->order_by('item_id', 'ASC');
Makes no difference, as it seems the order_by() or any sql queries are ignored if the second argument of the factory is given.
Another obvious error with that query is that the item_id = '', when it should contain all the elements.
So my question is how can I get access to the data stored in the pivot table, and actually how can I get access to the all items held by a particular user as I even had problems with that?
Thanks
By default, all of Kohana's ORM models expect the table's primary key to be 'id.' You need to set $_primary_key in your model to something else.
$user_item = ORM::factory('user_item', array('user_id' => $user, 'item_id' => $user->items));
I think you need to provide a single item_id value for this to work, not an array of objects.
Also, to find all entries for a single user you should be able to do this:
$user_items = ORM::factory('user_item', array('user_id' => $user));
Does that answer your question?