Delete multiple rows in YII2 - yii2

I have an array of objects fetched from database:
$masterListContacts = MasterListContacts::find()
->select('master_list_contacts.*')
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
->with('masterContact')
->where(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug])
->all();
Under certain circumstances, I need to delete all rows from the database represented in this array. But with both delete() and deleteAll() methods I got an error Call to a member function ... on array. Could someone tell me please which one is the best way to accomplish this?
UPDATE:
Here is my database structure.

Found better solution:
\Yii::$app
->db
->createCommand()
->delete('master_contacts', ['id' => $deletableMasterContacts])
->execute();
Where $deletableMasterContacts is array of master_contacts ids, which should be deleted

You can painlessly remove ->select('master_list_contacts.*').
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
performs the same work that ->joinWith('masterContact').
For delete entites try use this code:
MasterListContacts::deleteAll(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]);

Related

Laravel: DB Query returns stdclass instead of array

I've got the following:
$srv = DB::table('ads')
->join('ad_service','ad_service.ad_id', '=', 'ads.id')
->select('ads.id')
->whereIn('ads.id',[45789,46531])
->get();
Log::info($srv);
and log info gives me
49 => stdClass::__set_state(array(
'id' => '46531',
)),
50 =>
stdClass::__set_state(array(
'id' => '46531',
)),
51 =>
stdClass::__set_state(array(
'id' => '46531',
)),
What I would like to have:
return the entry ONCE, there are multiple entries with this id in the "ad_service" table , and i would like to retrieve it once.
its a many to many relationship.
also biggest problem, what is this stdclass set state?
I was expecting something like:
array('id' => '46531', ...,)
thanks guys.
EDIT:
Solved it using Eloquent:
$srv = Ad::whereIn('id',[46696,48982,...MORE IDS HERE])->get();
this returns not an object but a collection itself. i do not really know what #ourmandave meant with "you get a collection with std class objects" i mean obviously i could see that but i do not really know why i got it, and why i get it as i wish using eloquent.
Any answer to that would be appreciated:
Why does DB:: return this std class stuff and Eloquent returns the "wanted format"?
If you just want one record you could try:
$srv = DB::table('ads')
->join('ad_service','ad_service.ad_id', '=', 'ads.id')
->select('ads.id')
->whereIn('ads.id',[45789,46531])
->first();
Change the get to a first(). The reason you are getting multiple records is because get() returns a laravel collection of your ads.
You're actually getting back a lararvel Collection.
From the docs (https://laravel.com/docs/5.8/queries#retrieving-results)
The get method returns an Illuminate\Support\Collection containing the
results where each result is an instance of the PHP stdClass object.
You may access each column's value by accessing the column as a
property of the object:
foreach ($users as $user) {
echo $user->name;
}
There's a lot of methods they provide for collections to treat them like arrays.
(https://laravel.com/docs/5.8/collections#available-methods)
You might also try the distinct() method to get back one of multiples.
$srv = DB::table('ads')
->join('ad_service','ad_service.ad_id', '=', 'ads.id')
->select('ads.id')
->whereIn('ads.id',[45789,46531])
->distinct()
->get();
To convert a model and its loaded relationships to an array, you should use the toArray method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays
$srv = DB::table('ads')
->join('ad_service','ad_service.ad_id', '=', 'ads.id')
->select('ads.id')
->whereIn('ads.id',[45789,46531])
->get()
->toArray();
Print array:
Log::info($srv);

Multiple Fields with a GroupBy Statement in Laravel

Already received a great answer at this post
Laravel Query using GroupBy with distinct traits
But how can I modify it to include more than just one field. The example uses pluck which can only grab one field.
I have tried to do something like this to add multiple fields to the view as such...
$hats = $hatData->groupBy('style')
->map(function ($item){
return ['colors' => $item->color, 'price' => $item->price,'itemNumber'=>$item->itemNumber];
});
In my initial query for "hatData" I can see the fields are all there but yet I get an error saying that 'colors', (etc.) is not available on this collection instance. I can see the collection looks different than what is obtained from pluck, so it looks like when I need more fields and cant use pluck I have to format the map differently but cant see how. Can anyone explain how I can request multiple fields as well as output them on the view rather than just one field as in the original question? Thanks!
When you use groupBy() of Laravel Illuminate\Support\Collection it gives you a deeper nested arrays/objects, so that you need to do more than one map on the result in order to unveil the real models (or arrays).
I will demo this with an example of a nested collection:
$collect = collect([
collect([
'name' => 'abc',
'age' => 1
]),collect([
'name' => 'cde',
'age' => 5
]),collect([
'name' => 'abcde',
'age' => 2
]),collect([
'name' => 'cde',
'age' => 7
]),
]);
$group = $collect->groupBy('name')->values();
$result = $group->map(function($items, $key){
// here we have uncovered the first level of the group
// $key is the group names which is the key to each group
return $items->map(function ($item){
//This second level opens EACH group (or array) in my case:
return $item['age'];
});
});
The summary is that, you need another loop map(), each() over the main grouped collection.

Use IN clause in updateAll() method in CakePHP 3.x

I am using Cakephp 3.x and i want to update my single field for multiple ids. Something like this..
UPDATE mytable SET `status` = '1' WHERE ID IN (1,2,3)
Currently i am using query to perform this action using cakpehp
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN ('.$this->request->data('final_ids_string').')'])
->execute();
Well this does the trick for me but i want this to be performed using cakephp 3.xs' ORM method .. so i am trying to use this instead
$table->updateAll(['field' => $newValue], ['id' => $entityId]);
But this code is for single id only which i do not want.. i also do not want to use foeach loop to perform the same action. Instead i want an ID to be passed via array or comma seperated in any case and want to perform the same action.
Is there any way i can perform the same thing using ORM method using cakephp 3.x
Thanks
usinga updateAll or a query() objects to do a bulk update is the same thing as you can read in the manual at the end of this paragraph
so you can do
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN' => [1,2,3])
->execute();
or
$this->Leaveregisters->updateAll(
['leaveregister_status' => $this->request->data('status')]
['leaveregister_id IN' => [1,2,3]);
remember then when usin IN clause you have to pass an array. Read this part of the manual on how to create IN clause
You have to use array datatype for pass in IN CLAUSE
$in_condition= explode(",",$this->request->data('final_ids_string'));
$this->Leaveregisters->query()
->update()
->set(['leaveregister_status' => $this->request->data('status')])
->where(['leaveregister_id IN' => $in_condition])
->execute();
With updateAll() of Model
$table->updateAll(array(
// new values
),
array('id' => array(1,2,3,4,5,6))
);

Cakephp 3: Modifying Results from the database

In my database there is a content table and when fetching data from this table I would like to append field url to the results, which is based on slug field which is contained in the table. Anyway, I have seen a way to do this in the previous versions of cakephp using behavior for the model of this table and then modifying results in afterFind callback in the behavior class. But in version 3 there is no afterFind callback, and they recommend using mapReduce() method instead in the manual, but this method is poorly explained in the manual and I cant figure out how to achieve this using mapReduce().
After little bit of research I realized that the best way to append the url field field to find results is using formatResults method, So this is what I did in my finders:
$query->formatResults(function (\Cake\Datasource\ResultSetInterface $results) {
return $results->map(function ($row) {
$row['url'] = array(
'controller' => 'content',
'action' => 'view',
$row['slug'],
$row['content_type']['alias']
);
return $row;
});
});

Mass update in Laravel Eloquent or DB

Is there anyone who knows how to do this without the technique of doing it in a one query string. I mean the popular ways I see on the net is by looping in data(the updates) and generating a single update statement and then fire a query. Is it possible for an Eloquent Approach or DB without looping?
This is posible with Eloquent, it might be necessary to enable mass-assignment, but you will get an error if so.
$post_data = Input::all();
$model = Model::find($id);
$model ->fill($post_data);
$model ->save();
or
$post_data = Input::all();
Model::find($id)->update($post_data);
Yes, you can do that but in that case, you have to make the array of data that is a loop is needed to store the data in the array with respective field_name => value of the table.
The following is the example:
$Array = array(); //This is needed to hold data while looping over $YourData
$YourData - is the array of data you want to store in the respective table.
foreach ($YourData as $YourDatakey => $YourDatavalue ){
$Array = [
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
'table_column_name' => $YourDatavalue['value_from_array'],
...... and so on
];
}
$InsertQuery= YourModelName::create($Array);
PS:
YourModelName model file should have the columns in protected
$fillable = ['column1','column2'....];
You should use App\Models\ModelName; at the top of the file.