Delete multiple entities by id Cakephp3 - cakephp-3.0

Is there a more efficient way of deleting multiple entities by id
$data = $this->request->data ['missing_lexicon_id'];
foreach ( $data as $id ) {
$missingLexicon = $this->MissingLexicons->get ( $id );
$this->MissingLexicons->delete ( $missingLexicon )
}

This should work
$this->MissingLexicons->deleteAll(['MissingLexicons.column IN' => $keys]);
Where $keys is an array with the ids to be deleted.

Most efficient way to delete multiple entities using deleteALL().
$this->MissingLexicons->deleteAll(['id IN' => $multiItemsArray]);
OR
$this->MissingLexicons->deleteAll(['id' => $multiItemsArray[]]);
MissingLexicons = Your Model name.
$multiItemsArray = Your deleted entities id
Read More Here

Related

Yii relation — MySQL foreign key

Tables in MySQL:
field:
id pk
field_option
id pk
feild_id int(11)
ALTER TABLE `field_option` ADD CONSTRAINT `option_field` FOREIGN KEY ( `feild_id` ) REFERENCES `agahi_fixed`.`field` (
`id`
) ON DELETE CASCADE ON UPDATE RESTRICT;
Relation Field model:
return array(
'fieldOption' => array(self::HAS_MANY, 'FieldOption', 'feild_id'),
);
Relation FieldOption model:
return array(
'feild' => array(self::BELONGS_TO, 'Field', 'feild_id'),
);
In controller:
if(Field::model()->exists('cat_id = :catId', array(":catId"=>$_POST['catid']))){
$criteria=new CDbCriteria;
//$criteria->select='*';
$criteria->condition='cat_id=:catId';
$criteria->params=array(':catId'=>$_POST['catid']);
$criteria->with = 'fieldOption';
$field=Field::model()->findAll($criteria);
header('Content-type: application /json');
$jsonRows=CJSON::encode($field);
echo $jsonRows;
}
but it does not work with just select records in field table.
Why?
this way you won't achive what your looking for,
when you fetch your records using with it will fetch associated records, meaning : eager loading not lazy, but when you json encode your model, It will get attributes of your main model, not any relations, If you want any related data to get encoded with the model, you have to explicitly say so. I suggest make an empty array :
$result = array();
make a loop over your model and append to this result, from model to related model
foreach($field as $model)
{
$record = $model->attributes; // get main model attributes
foreach($model->fieldOption as $relation)
$record['fieldOption'][] = $relation->attributes; // any related records, must be explicitly declared
$result[] = $record;
}
now you have exactly what you need, then echo it
echo CJSON::encode($result);

Zend Framework 2: LEFT JOIN issue

public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
Here is my method. It simply selects all records from users_interests with user_id = $userID and joins the 'interests' table. So far, so good, but when trying to display the fetched results, the fields from the joined table just do not exist. Here is the dump of the $result:
Zend\Db\ResultSet\ResultSet Object
(
[allowedReturnTypes:protected] => Array
(
[0] => arrayobject
[1] => array
)
[arrayObjectPrototype:protected] => Object\Model\UsersInterests Object
(
[settings_id] =>
[user_id] =>
[interest_id] =>
)
[returnType:protected] => arrayobject
[buffer:protected] =>
[count:protected] => 2
[dataSource:protected] => Zend\Db\Adapter\Driver\Pdo\Result Object
(
[statementMode:protected] => forward
[resource:protected] => PDOStatement Object
(
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN `interests` ON `users_interests`.`interest_id` = `interests`.`interest_id` WHERE `user_id` = :where1
)
[options:protected] =>
[currentComplete:protected] =>
[currentData:protected] =>
[position:protected] => -1
[generatedValue:protected] => 0
[rowCount:protected] => 2
)
[fieldCount:protected] => 6
[position:protected] =>
)
I badly need help on this because I am supposed to finish my project until Sunday. Thanks in advance.
You can use the following to apply left join. $select::JOIN_LEFT instead of 'left'.
public function getInterests($userID) {
$result = $this->tableGateway->select(function (Select $select) use ($userID) {
$select->join('interests', 'users_interests.interest_id = interests.interest_id', array('*'), $select::JOIN_LEFT);
$where = new Where();
$where->equalTo('user_id', $userID);
$select->where($where);
});
return $result;
}
It seems you have a problem in the WHERE clause of the join. This also shows in the error here:
[queryString] => SELECT `users_interests`.*, `interests`.* FROM `users_interests` LEFT JOIN .
`interests` ON `users_interests`.`interest_id` = `interests`.`interest_id`
WHERE `user_id` = :where1
Try this:
$select->from($this->table)
->join('interests', 'users_interests.interest_id = interests.interest_id',
array('*'), 'left');
$where = new Where();
$where->equalTo('user_id', $userID) ;
$select->where($where);
I can not follow your code completely, like here:
$this->tableGateway->select(function (Select $select) use ($userID) {
But, here is a very nice article on this. I think, you can simplify your code a little.
Have you iterated over the resultset? You can see there's two matching rows:
[rowCount:protected] => 2
You have a ResultSet object, but it will not load any of the rows until requested, they are "lazy loaded" when you iterate over the object.
You can force the resultset to get them all for you:
var_dump($resultSet->toArray()); // force load all rows
or iterate over the ResultSet:
foreach($resultset as $row) {
var_dump($row); // each row loaded on request
}
I have written about this before and maybe it will help you as well.
TableGateway with multiple FROM tables

Update with Zend_DB on multiple rows

I am using Zend Framework. I have tree tables. Users and Groups and one table linking them.
I want to increment a field from users of a given group. To increment one User I do:
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where[] = $db->quoteInto('id = ?', $user);
$db->update($table, $update, $where);
I tried to use multiple wheres.
I have no clue how to join the tables in a where with Zend.
To use a JOIN with Zend_Db_Table, you have to disable the integrity check.
See example #27 in the ZF Reference Guide for Zend_Db_Table:
$table = new Bugs();
// retrieve with from part set, important when joining
$select = $table->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->where('bug_status = ?', 'NEW')
->join('accounts', 'accounts.account_name = bugs.reported_by')
->where('accounts.account_name = ?', 'Bob');
$rows = $table->fetchAll($select);
Note that disabling the integrity check will also disable some of the automagic of the resulting recordset:
The resulting row or rowset will be
returned as a 'locked' row (meaning
the save(), delete() and any
field-setting methods will throw an
exception).
Load $num with a array of id's from a given group
The following code will do the job
$table = 'users';
$update = array(
'ACLVersion' => new Zend_Db_Expr('ACLVersion + 1')
);
$where = $db->quoteInto('id IN (?)', $num);
$db->update($table, $update, $where);

CI: Querying two tables in the model, explode

i'm thinking about this for days now and don't come to grasps (since i'm relativley new to MVC and CI). I'm not even sure whether this is an issue with MVC, MySQL or arrays.
Situation: 2 MySQL tables
Table data: id, title, list
Table values: id, name
Querying the data table results in an array like the following (excerpt):
[4] => Array
(
[id] => 3
[title] => Foo
[list] => 1,2,3,4,6,14
)
[5] => Array
(
[id] => 4
[title] => Bar
[list] => 2,6,9,12
)
The field list contains comma separated values that correspond to some IDs of the values table like
[3] => Array
(
[id] => 12
[name] => 'value12'
)
What I try to do for each row is:
take the list-values & explode it into an array
check with the result set from the values-table (via in_array() method)
return the name values of the IDs if
include it somehow into the main result set (e.g. as a 2-dimensional array):
[5] => Array (
[id] => 4
[title] => Bar
[list] => Array (
[0] => value6
[1] => value12
...
)
)
My naive approach so far was to
run a query on each of the 2 tables
compare the 2 result sets via in_array
My main problem (while trying to strictly separate model, controller and view): How can I include the name field from the values-table in the "main loop" of the data table result set?
if($q->num_rows() > 0)
{
$data[] = $q->result_array();
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
If I use the following (cumbersome) approach i naturally get a new item each time:
foreach ($q->result_array() as $row)
{
$data[]['id'] = $row['id'];
$data[]['title'] = $row['title'];
$data[]['list'] = $row['year'];
}
Since this is a MySQL database I see no way to do the explode and the comparison in SQL (with LIKE or something else).
Any hint, even a simple link to an info bit, is highly appreciated.
Thanks a trillion!
fab
There is a many-to-many relationship between lists and list values. The conventional way to model this in a relational database is to create a joining table. So I'd structure your schema like this.
lists : list_id, title
values : value_id, name
list_values : list_id, value_id
list_values is the joining table. It links lists with values.
To build a list you could have the following functions in your model
function build_list($list_id)
{
$list = $this->get_list($list_id);
$list->values = $this->get_list_values($list_id);
return $list;
}
function get_list($list_id)
{
$sql = 'select * from lists where list_id=?';
return $this->db->query($sql, array($list_id))->row();
}
function get_list_values($list_id)
{
$sql = 'select v.value_id, v.name
from list_values lv
join values v on v.value_id=lv.value_id
where lv.list_id=?';
return $this->db->query($sql, array($list_id))->result();
}

categories and items 1 big array

I've made some search on the forum without any good answers for my problem. If I missed something, feel free to link me to the question!
What I need to do is simple: a function that returns an array of the full tree of my categories and items. I only have 1 depth (item and a cat_id), so no recursion involved (though if you have a recursive solution, I would gladly accept it).
Right now, I've done this, but it's pretty bad, since I do multiple queries...
function build_tree()
{
global $wpdb;
$cats = $wpdb->get_results("SELECT * FROM wp_catering_cats");
foreach($cats as &$cat)
{
$id = $cat->id;
$cat->items = $wpdb->get_results("SELECT * FROM wp_catering_items WHERE cat_id = $id");
}
return $cats;
}
My tables are really simple:
wp_catering_items
id, cat_id, name, price
wp_catering_cats
id, name
Here is an exemple the results array I want:
Array
(
[0] => array
(
[id] => 1
[name] => Cat #1
[items] => Array
(
[0] => array
(
[id] => 1
[cat_id] => 1
[name] => Item #1
[price] => 5
),
...
)
),
...
);
If something is not clear, feel free to comment!
Thanks!
EDIT
I've made some modifications using the code bellow, but I' pretty sure there's a neater way to do this. Having to order one DESC and one ASC just doesn't sounds right..
function build_tree()
{
global $wpdb;
$cats = $wpdb->get_results("SELECT * FROM wp_catering_cats ORDER BY id DESC");
$items = $wpdb->get_results("SELECT * FROM wp_catering_items ORDER BY cat_id ASC");
$item = array_pop($items);
foreach($cats as &$cat)
{
while($item->cat_id == $cat->id)
{
$cat->items[] = $item;
$item = array_pop($items);
}
}
print_r($cats);
}
If you are just trying to optimize, then do the simple thing, instead of only grabbing the items for the specific cat you are on, grab all the items at once, and order them by catID. Then loop through your cats, and pop items off your item results until you hit the next cat.
function build_tree()
{
global $wpdb;
$cats = $wpdb->get_results("SELECT * FROM wp_catering_cats order by cat_id asc");
$items = $wpdb->get_results("SELECT * FROM wp_catering_items ORDER BY cat_id asc");
foreach($cats as &$cat)
{
$id = $cat->id;
$item = array_pop($items)
while($item['cat_id'] == $id)
{
$cats->item[] = $item;
$item = array_pop($items)
}
#do a little bookkeeping so you next cat gets its first item, and zero item cats get skipped.
}
}
Update: Thanks for the comment.. Forgot to add the pop in the while loop!
Second update: use array_shift instead of array_pop if you don't want reverse ordering to be a problem...